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.

思路:这道题就是一个大数加法。从右往左,最低位加上1,然后判断result[n-1]是不是大于9,即取其除数向前进位。

class Solution {

public:

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

        vector<int> result(digits);

        int n=digits.size();

        if(n==0)

            return result;

        int plus=1;

        int temp=0;

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

        {

            temp=result[i]+plus;

            plus=temp/10;

            result[i]=temp%10;

        }

        if(plus>0)

        {

            result.insert(result.begin(),plus);

        }

        return result;

    }

};

 

 

你可能感兴趣的:(one)