题目
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,则+1并返回,否则将值改为0,最后首位改为1,末尾添加0.
代码
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
for(int i=digits.size()-1; i>=0; i--) {
if(digits[i] != 9) {
digits[i]++;
return digits;
} else {
digits[i] = 0;
}
}
digits[0] = 1;
digits.push_back(0);
return digits;
}
};