题目:
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.
思路:在原数字上加1,如果发生进位的话只有一种情况:
例如:99999+1 = 100000;
所以对于进位的情况,只需要在最后添加一个零,而把第一个数字变为1即可。
代码:
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int> result = digits;
int num = result.size();//获取数组大小
int plus = 1;//加数
for(int i=num-1;i>=0;i--)
{
int temp = result[i];
result[i] = (result[i]+plus)>9?(result[i]+plus-10):(result[i]+plus);
plus = (temp+plus)>9?1:0;
}
if(plus==1)
{
result.push_back(0);
result[0]=1;
}
return result;
}
};