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.
先把最后一位加一,然后从后往前遍历,计算进位。
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int len = digits.size();
digits[len-1]++;
int index = len-1;
while (digits[index] >= 10 && index > 0) {
//进位
int next = digits[index] / 10;
digits[index] %= 10;
digits[index-1] += next;
index--;
}
//处理第一位的进位
if (digits[0] >= 10) {
digits[0] %= 10;
digits.insert(digits.begin(), 1);
}
return digits;
}
};

被折叠的 条评论
为什么被折叠?



