66. Plus One
2018-01-23 本文已影响0人
i_Eloise
Question
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
- first attempt
这不是一个好的答案
因为我没有考虑到vector的长度 如果它很长,就算使用long long也是无法储存sum的,而且还使用了2次循环
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
long long sum=0;
for(unsigned i =0;i <digits.size();i++)
sum=sum*10+digits[i];
sum = sum+1;
vector<int> ve;
if(sum==0)
return ve;
while(sum!=0)
{
ve.insert(ve.begin(),sum%10);
sum=sum/10;
}
while(ve.size()!=0&&ve.front()==0)
ve.erase(ve.begin());
return ve;
}
};
- improved
改进后
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int>::reverse_iterator it;
int carry=1;
for(it = digits.rbegin();it!=digits.rend();it++)
{
if(carry==1)
{
if( ((*it)+carry)==10 )
{
(*it)= 0;
carry=1;
}
else
{
(*it)=(*it)+carry;
carry = 0;
}
}
else
break;
}
if(carry ==1)
digits.insert(digits.begin(),1);
return digits;
}
};