题目:
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) {
int n = digits.size();
if(digits[n-1] < 9) {
digits[n-1] += 1;
return digits;
}
bool jin_wei = 1;
for(int i = n-1; i >= 0; i--) {
if(jin_wei == 1) {
if(digits[i] < 9) {
digits[i] += 1;
jin_wei = 0;
}
else {
digits[i] = 0;
}
}
else {
break;
}
}
if(jin_wei == 1) {
digits.insert(digits.begin(), 1);
}
return digits;
}
};
思路:很简单,从最低位开始,需要进位则该位置0,记录进位;如果不需要进位,则跳出循环;如果最高位需要进位,在vector头部插入1即可。