问题描述
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操作
解题思路
对末位数字进行加1操作后,只需要考虑如果末位为9的进位,以及若首位需要进位,则需要在首位插入1
代码块
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int n = digits.size();
for (int i = n - 1; i >= 0; i--) {
if (digits[i] == 9)
digits[i] = 0;
else {
digits[i] += 1;
return digits;
}
}
if (digits.front() == 0)
digits.insert(digits.begin(), 1);
return digits;
}
};