[leetcode] Plus One


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.

Show Tags

注意进位,从vector末尾扫向开头。

class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        if(digits.size() == 0) return digits;
        (*(digits.end() - 1))++;
        for(int i = digits.size() - 1; i > 0; i--){
            if(digits[i] == 10){
                digits[i] = 0;
                digits[i - 1]++;
            }
            else{
                break;
            }
        }
        if(digits[0] == 10){
            digits[0] = 0;
            digits.insert(digits.begin(), 1);
        }
        return digits;
    }
};

Untitled

 

 

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.