HappyLeetcode44: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

 

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

值得注意的一点是当结果位数需要增大的时候需要为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()处增添了新的元素。
posted @ 2015-01-13 09:19  程序员小王  阅读(126)  评论(0编辑  收藏  举报