首页 > 移动平台 > 详细

HappyLeetcode44:Plus One

时间:2015-01-13 10:20:33      阅读:242      评论: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

 

这道题的题目意思花了好长时间才能明白。明白了之后还好,感觉还可以做一做。

值得注意的一点是当结果位数需要增大的时候需要为vector增大空间。这个需要用到vector中的insert。这个还是头一次用到,感觉不错。

代码奉上:

class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        int value=digits.size()-1;//设置长度
        while(value>=0)
        {
            if(digits[value]<9)
            {
                digits[value]+=1;
                break;
            }
            else
            {
                digits[value]=0;
                value--;
            }
        }
        value++;
        if(value==0&&digits[value]==0)
        {
            digits.insert(digits.begin(),1);//这句话十分关键
        }
        return digits;
    }
};
说一说vector对象中insert的使用方法:vector向量容器中使用insert()方法,可以在vector对象的任意位置前插入一个新的元素,书上说,insert()方法要求插入的位置,是元素迭代器的位置,而不是元素的下标。如上面代码中实在digits.begin()处增添了新的元素。

HappyLeetcode44:Plus One

原文:http://www.cnblogs.com/chengxuyuanxiaowang/p/4220406.html

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