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,返回数组
class Solution {
public:
    static vector<int> plusOne(vector<int>& digits) {
        int i = digits.size();
        while (i > 0 && digits[--i] == 9)        //如果末尾的值为9;且不为首元素时
        {
            digits[i] = 0;
            if (i == 0)            //如果9已经是首元素了,则插入一个0
            {
                digits.insert(digits.begin(), 0);
            }
            
        }
        digits[i] += 1;            //在最前面一个不是9的值+1
        return digits;
    }
};
posted @ 2015-10-23 09:09  dylqt  阅读(120)  评论(0编辑  收藏  举报