[LeetCode]Plus One

Given a number represented as an array of digits, plus one to the number.

思考:大数相加的思想。flag是进位标记。

class Solution {

public:

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

        int len=digits.size();

        bool flag=false;

        digits[len-1]+=1;

        int i=len-1;

        if(digits[i]>9) flag=true;

        while(flag&&i>0)

        {

            digits[i]=digits[i]%10;

            digits[i-1]+=1;

            if(digits[i-1]>9) flag=true;

            else flag=false;

            i--;

        }

        if(digits[0]>9)

        {

            digits[0]=digits[0]%10;

            vector<int> ans;

            ans.push_back(1);

            for(i=0;i<len;i++)

            {

                ans.push_back(digits[i]);

            }

            return ans;

        }

        return digits;

    }

};

  

你可能感兴趣的:(LeetCode)