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
- 1 ≤ digits.length ≤ 100
- 0 ≤ digits[i] ≤ 9
- No leading zeros, except the number 0 itself
Edge cases to test
- All 9s:
[9, 9]→[1, 0, 0] - A single digit
- No carry at all
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] + digitsC++
#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
- Happy Number (Easy)
- GCD and LCM (Euclid) (Easy)
- Count Primes (Sieve of Eratosthenes) (Medium)
- Pow(x, n) (Medium)
- Count Good Numbers (mod 1e9+7) (Medium)
- Multiply Strings (Medium)
- Reverse Integer (Medium)
- String to Integer (atoi) (Medium)
- Detect Squares (Medium)
- Random Pick with Weight (Medium)
- Shuffle an Array (Medium)
- Linked List Random Node (Medium)
- Pascal's Triangle (Easy)
- nCr mod p (Medium)
- Max Points on a Line (Hard)