Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
思路:
作为一道Array的题目,这个题目比较简单。需要考虑加法的运算法则:1.末位加一;2,每一位“逢十近一”;3.如果最高位被进位加一以后变成十,就在最高位前面加一位“1”。
代码如下:
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
++digits.back();
for(int i = digits.size() - 1; i > 0 && digits[i] == 10; --i){
digits[i] = 0;
digits[i - 1]++;
}
if(digits[0] == 10){
digits[0] = 0;
digits.insert(digits.begin(), 1);
}
return digits;
}
};