首页 > 代码库 > LeetCode:Plus One

LeetCode: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.


思路:先将list翻转,再在list尾部加一个0。如果第一个数非9,则直接将其加1;否则遍历list,将遇到的第一个非9的数加1,其前面的数都置零。如果list的最后一个数为0,则将其删除。最后将list再翻转一次即得到结果。


代码:

vector<int> Solution::plusOne(vector<int> &digits)
{
    reverse(digits.begin(),digits.end());
    digits.push_back(0);
    int length = digits.size();
    bool flag = false;
    for(int i = 0;i < length;i++)
    {
        if(digits[i] == 9)
        {
            flag = true;
            continue;
        }
        else
        {
            if(flag)
            {
                for(int j = 0;j < i;j++)
                    digits[j] = 0;
                digits[i]++;
                break;
            }
            else
            {
                digits[i]++;
                break;
            }

        }
    }
    if(digits[length-1] == 0)
        digits.pop_back();
    reverse(digits.begin(),digits.end());
    return digits;
}


LeetCode:Plus One