leetcode[66]Plus One

2093 ワード

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.
class Solution {

public:

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

{

    int len=digits.size();

    int flag=0;

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

    {

        int temp=0;

        if (i==len-1)

        {        

            temp=digits[i]+1;

        } 

        else

        {

            temp=digits[i]+flag;

        }

        digits[i]=temp%10;

        flag=temp/10;

    }

    if (flag>0)

    {

        digits.insert(digits.begin(),flag);

    }

    return digits;

}

};