LeetCode 66. Plus One

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
解析:
用vector表示非负的数值,计算加1后的内容,并且以vector的形式返回。
既然是十进制加1,就要考虑进位的情况,一个变量存储进位数值,一个变量标记当前数值加进位后的数值。具体代码如下:
[cc lang=”C++”]
class Solution {
public:
vector plusOne(vector& digits) {
add(digits, 1);
return digits;
}
void add(vector &digits, int digit){
int c = digit;//表示当前位的进位
for(auto it = digits.rbegin(); it != digits.rend(); it ++)
{
*it += c;
c = *it / 10;
*it %= 10;
}
if(c>0)//遍历结束后仍有进位
digits.insert(digits.begin(), 1);
}
};
[/cc]
结果:

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据