LeetCode题解:Plus One


Plus One


Given a number represented as an array of digits, plus one to the number.
思路:
关键在于计算进位。
题解:
class Solution {
public:
    vector plusOne(vector &digits) {
        int incr = 1;
        for(auto d = digits.rbegin(); d != digits.rend(); ++d)
        {
            *d += incr;
            if (*d >= 10)
            {
                *d -= 10;
                incr = 1; 
            }
            else
                incr = 0;
        }
        if (incr)
            digits.insert(begin(digits), 1);
        
        return digits;
    }
};


你可能感兴趣的:(数据结构和算法)