Skip to content

66.Plus One #27

@niuworld

Description

@niuworld

Question:

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.

Solution:

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int len = digits.size();
        int pos = len - 1;
        while(pos >= 0){
            if ( digits[pos] != 9 ){
                ++digits[pos];
                break;
            }
            digits [pos] = 0;
            pos --;
        }
        if ( pos == -1)
          digits.insert(digits.begin(), 1 );
        return digits;
    }
};

Note: use of vector::insert

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions