66. Plus One

来源:互联网 发布:高通垄断 知乎 编辑:程序博客网 时间:2024/05/20 05:05

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
                
 bool carry = true;
        
        for(int i=digits.size()-1; i >= 0 && carry; i--) {
            carry = (++digits[i]%=10) == 0;
        }


        if(carry) {
            digits.insert(digits.begin(), 1);
        }
    
        return digits;
    }
};

原创粉丝点击