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.

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;
    }
};
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;         
    }
};
上一篇下一篇

猜你喜欢

热点阅读