题目:
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.
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
if(digits.empty()) return digits;
vector<int> res;
int carry = 1;
//先低位优先存储,然后反转
int i = digits.size()-1;
for(; i >= 0; --i){
int tmp = digits[i] + carry;
res.push_back(tmp%10);
carry = tmp / 10;
if(!carry) {--i; break;}//没进位了。(!!!注意:该位已经处理过了,所以break前别忘了--i)
}
for(; i >= 0; --i){//将剩下的高位直接放入res
res.push_back(digits[i]);
}
if(carry) res.push_back(carry);
reverse(res.begin(), res.end());//反转,变为高位优先存储
return res;
}
};