66.Plus One
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
给定一个不为空的自然数数组,需要为其加1,假设除了0外,数组第一个不为0.
示例 1:
输入: [1,2,3]
输出: [1,2,4]
示例 2:
输入: [4,3,2,1]
输出: [4,3,2,2]
注意点:
1.进位:若当前位+1后为10,则需向前一位进1;若最前位还要进位,则要在最前位前插入一个数字1.
2.时间复杂度:若当前位无需进位,则终止循环,因为前面不会再发生变化。
代码:
vector<int> plusOne(vector<int>& digits) {
int temp;
int add=1;
for(int i=digits.size()-1;i>=0;--i)
{
temp=digits[i];
temp+=add;
if(temp==10)
{
digits[i]=0;
add=1;
}
else
{
digits[i]=temp;
add=0;
break;
}
cout<<digits[i]<<" ";
}
if(add==1)
{
digits.insert(digits.begin(), 1);
}
return digits;
}