题目:

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,主要需要处理的就是进位的问题。由于是加1,因此只有在当前数字为9的时候采进位。如果在数组的第0个元素上还需要进位,那么就需要在该元素前面增加一个数字1。


代码:

class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        vector<int>::iterator iter = digits.end();
        while(*(--iter)==9){
            *iter=0;
            if(iter==digits.begin()){
                digits.insert(digits.begin(),1);
                return digits;
            }
        }
        *iter+=1;
        return digits;
    }
};