1. Problem Description
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.
一个十进制非负整数,用vector存起来,计算加1之后的结果,返回的同样是一个vector。
2. My solution
So easy~
vector<int> plusOne(vector<int>& digits)
{
int len=digits.size();
int pre=0;
for(int i=len-1; i>=0; i--)
{
if(i==len-1)
digits[i]=digits[i]+1+pre;
else
digits[i]=digits[i]+pre;
if(digits[i]>=10)
{
digits[i]%=10;
pre=1;
}
else
pre=0;
}
//处理最后一位
if(pre==1)
{
digits.push_back(0);
for(int i=len; i>=1; i--)
digits[i]=digits[i-1];
digits[0]=1;
}
return digits;
}