66. Plus One
来源:互联网 发布:飞思卡尔用keil编程 编辑:程序博客网 时间:2024/06/08 12:14
问题描述
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
题目链接
思路分析
给出一个用非空数组表示的整数,要求计算这个整数加一的结果。
问题的关键在于进位,如果最高位是9的话需要升一位,只有 999……99 这样的情况才会出现,正常情况还是从最后一位看起,逢9变0,非9加1即可。进位一定出现在循环结束之后,只需要看数组中的第一个元素有没有变成0即可。
代码
class Solution {public: vector<int> plusOne(vector<int>& digits) { int n = digits.size(); for(int i = n-1; i > -1; i--){ if (digits[i] == 9 ) digits[i] = 0; else{ digits[i] += 1; break; } } if (digits[0] == 0){ digits[0] = 1; digits.push_back(0); } return digits; }};
时间复杂度:O(n)
反思
思考了很久,主要是对于进位的处理没有想清楚,还是要想清楚边界条件,以及在对问题关键的把握要准确。
阅读全文
0 0
- [LeetCode]66.Plus One
- LeetCode --- 66. Plus One
- [Leetcode] 66. Plus One
- [leetcode] 66.Plus One
- 66. Plus One
- 66. Plus One
- [leetcode] 66. Plus One
- Leetcode-66. Plus One
- 【leetcode】66. Plus One
- 66. Plus One
- 66. Plus One LeetCode
- 66. Plus One
- 66. Plus One
- 66. Plus One
- 66. Plus One
- 66. Plus One
- 【LeetCode】66. Plus One
- [LeetCode]66. Plus One
- 第三方所能用到的库文件的compile代码
- win10下编译linphone-desktop出现的错误以及解决办法
- 04 Nifty自定义带图片的下拉框
- Flume 入门--几种不同的Sources
- NOIP2010提高组
- 66. Plus One
- 05 Gradle打包jmonkey开发的Desktop应用
- SQL重复记录查询的几种方法
- Dubbo了解
- table宽度失效-table布局的问题
- hdu 4825 Xor Sum(01字典树)
- SQL Server 对比两个数据库的索引
- Oracle迅速取到一个表的所有列的列名的方法
- 解析Android Studio 2.2 Native新特性