Leetcode – Plus One

Name: Plus One
Difficulty: Easy
Description: Increment the large integer by one and return the resulting array of digits.


Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].

Feels like I hacked this one, I also modified the vector in place which is probably not what was expected. Initially I was pushing the vector into a unsigned long long, adding one to it, then moving it back into a vector. But the test data included some very large numbers which caused runtime errors. In the end I used this caveman approach:

vector<int> plusOne(vector<int>& digits) {
    if (digits.back() != 9) {
        digits[digits.size() - 1] += 1;
        return digits;

    auto i = digits.end() - 1;

    while (i > digits.begin() && *i == 9) {
        *i = 0;

    if (*i != 9) {
        *i += 1;
        return digits;

    *i = 1;

    return digits;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s