Plus One

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.

//不要再装逼使用unsigned int,这里使用UINT i,当i==0时进行i--,嘿,溢出了,循环继续

class Solution {

public:

    vector<int> plusOne(vector<int>& digits) {

        

        vector<int> res;

        if(!digits.size()) return res;

        

        bool sign=true;

        int i,j,n=digits.size();

        

        if(digits[n-1]!=9) //最后一位非9

        {

            digits[n-1]+=1;

            return digits;

        }

        

        for(i=n-1;i>=0;i--)

        {

            if(sign)

            {

                if(digits[i]==9)

                {

                    res.push_back(0);

                    if(!i) res.push_back(1); //尽头补一位

                }else

                {

                    sign=false;

                    res.push_back(digits[i]+1);

                    for(j=i-1;j>=0;j--)

                    {

                        res.push_back(digits[j]);

                    }

                }

            }

        }

        

        std::reverse(res.begin(),res.end());

        return res;

    }

};

 

你可能感兴趣的:(one)