Algo-Sim › Math & Geometry

Plus One

Easy · Math & Geometry · step through it in Java, Python and C++ on your own input

Add 1 to a number stored as digits: walk from the right turning 9s into 0s until a digit can absorb the carry. Only all 9s grow the array.

Problem

A large integer is given as an array digits, most significant digit first, with no leading zeros. Add one to it and return the resulting array of digits.

Constraints

Edge cases to test

Follow-up questions

How do you add two digit arrays?
Walk both from the right with a carry, like Add Two Numbers on linked lists: O(max(m, n)).
Why not convert to an integer?
The digit array can be longer than any fixed-width integer.

Solution

Java

public int[] plusOne(int[] digits) {
    for (int i = digits.length - 1; i >= 0; i--) {
        if (digits[i] < 9) {
            digits[i]++;
            return digits;
        }
        digits[i] = 0;
    }
    // Only all nines get here: 99…9 + 1 = 100…0.
    int[] result = new int[digits.length + 1];
    result[0] = 1;
    return result;
}

Python

def plus_one(digits):
    for i in range(len(digits) - 1, -1, -1):
        if digits[i] < 9:
            digits[i] += 1
            return digits
        digits[i] = 0
    # Only all nines get here: 99…9 + 1 = 100…0.
    return [1] + digits

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> plusOne(vector<int> &digits) {
        for (int i = int(digits.size()) - 1; i >= 0; i--) {
            if (digits[i] < 9) {
                digits[i]++;
                return digits;
            }
            digits[i] = 0;
        }
        // Only all nines get here: 99…9 + 1 = 100…0.
        vector<int> result = vector<int>(int(digits.size()) + 1);
        result[0] = 1;
        return result;
    }
};

More Math & Geometry problems