PlusOne

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

class PlusOne{
public:
    vector<int> plusOne(vector<int> &digits){
        int length = digits.size();
        if(digits[length - 1] < 9){
            digits[length - 1] += 1;
            return digits;
        }
        bool carry = 1;
        for(int i = length -1; i >= 0; i--){
            if(carry == 1){
                if(digits[i] < 9){
                    digits[i] += 1;
                    carry = 0;
                }else{
                    digits[i] = 0;
                }
            }else{
                break;
            }
        }
        if(carry == 1){
            digits.insert(digits.begin(),1);
        }
        return digits;
    }
};
点赞