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.
给定一个用数组表示的一个数,对它进行加一操作。
每一个数位都存储在数组的一个位置上。数组下标从大到小表示数位从低位到高位。
解题思路
直接求解,设置一个进位标志sign,初值为1,表示加1,从最低位开始tmp = a[x] + sign,
a[x] = tmp%10,
sign= tmp/10,如果sign不为0对下一位再进行操作,直到所有的数位处理完或者sign为0就退出,
如果最后还有sign不为0说明整个数组要扩展一个数位。
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int sign=1;
int sum=0;
vector<int> temp(digits.size(),0);
for(int i=digits.size()-1;i>=0;i--){
sum = sign+digits[i];
sign = sum/10;
temp[i] = sum%10;
}
if(sign>0){
temp.insert(temp.begin(),sign);
}
return temp;
}
};