[LeetCode]66. Plus One

Problem

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.

1
2
3
4
5
6
7
8
9
10
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.

给定一个整数数组,依次由高位到低位存储. 返回数组代表整数加1后的结果.

Solution

Analysis

整数加法. 数据由高位到低位依次存储在数组中.数据加法运算从低位到高位依次运算,两个数低位对齐,同时要处理进位位.这里如果最后还要进位位,在数组头部插入一个数1.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int carry = 1;

for (int i=digits.size()-1; i>=0 && carry; i--){
int sum = digits[i] + carry;
carry = sum / 10;
digits[i] = sum % 10;
}
if (carry)
digits.insert(digits.begin(), 1);

return digits;
}
};
您的支持就是我更新的最大动力!谢谢!