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

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

看题意,意思为:
给定一个以数字数组表示的数字,再加一。

这道题目具体的意思为:
比如给定一个digits数组{1,2,3,4},那就组成了一个数字1234,把这个数+1=1235,用数组返回1235的结果。

我们需要着重考虑的是如果结果位数变多,那么数组就会溢出。我们要处理好进位的问题。

代码如下:

class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        int size=digits.size();
        int i=0;
        for(i=size-1;i>=0;--i)
        {
            if(digits[i]!=9)
            {
                digits[i]++;
                return digits;
            }
            else
            {
                digits[i]=0;
            }
        }
        if(i<0)
        {
            digits.insert(digits.begin(),1);
        }
        return digits;
    }
};

猜你喜欢

转载自blog.csdn.net/baidu_37964071/article/details/81007763