码迷,mamicode.com
首页 > 其他好文 > 详细

Plus One

时间:2015-10-23 10:12:56      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
};

Plus One

标签:

原文地址:http://www.cnblogs.com/dylqt/p/4903426.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!