原题:
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.
思路:
从最后一位开始读,每位加一查看是否有超位。超位进位,最后如果没有位可进了在vetor首位插入新元素。
代码:
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int carry = 0;
vector<int> res;
int i;
for ( i = digits.size()-1; i>=0; i-- ){
digits[i] = 1+carry+digits[i];
carry = digits[i]/10;
digits[i] %= 10;
}
if(carry) digits.insert(digits.begin(),1);
return res;
}
};
这个的问题是1. return的res最终都没有值,因为过程中没有给它赋值。2. 逻辑错误,是最后一位加一并不是每一位都加一!
更改代码:
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int i;
for ( i = digits.size()-1; i>=0; --i ){
if(digits[i]==9) digits[i] = 0;
else {
++digits[i];
return digits;
}
}
if(i<0) digits.insert(digits.begin(),1);
return digits;
}
};