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次循環(huán)
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
改進(jìn)后
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;
}
};