首页 > 其他 > 详细

[Leetcode] Plus One

时间:2014-10-25 22:55:05      阅读:351      评论: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.

 

Tag:

Array; Math

 

体会:

这道题就是遵循着正常加法的模式,就是99..9这样情况的时候,要在最前位插入一个1。

class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        // follow the basic maths, pay attention to 99..9
        int n = digits.size();
        for (int i = n - 1; i >= 0; i--) {
            if ( digits[i] < 9) {
                // safe, + 1 and end
                digits[i]++;
                return digits;
            } 
            digits[i] = 0;
        }
        // if comes here, it is 99..9
        digits.insert(digits.begin(), 1);
        return digits;
    }
};

 

[Leetcode] Plus One

原文:http://www.cnblogs.com/stevencooks/p/4051023.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!