An array of digits represents a non-negative integer, most significant digit first. Return the array after adding one to the number.
Video coming soon
We're producing a video walkthrough — check back soon.
An array of digits represents a non-negative integer, most significant digit first. Return the array after adding one to the number.
The array here isn't a list of independent numbers — it's a single number spread across cells. Getting comfortable with that framing, plus carry propagation from the least significant digit, sets up every later in-place digit and array manipulation problem.
Whenever a prompt describes an array as the digits of one number, expect a reverse (right-to-left) traversal that propagates a carry, not a normal left-to-right scan.
Walk the array from the last digit to the first. Add 1 to the current digit; if the result is less than 10, no carry is needed and you can stop immediately. If it rolls over to 10, set that digit to 0 and continue the carry into the next digit to the left. If the carry survives past the first digit (every digit was 9), prepend a new leading 1.
class Solution {
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;
}
int[] withCarry = new int[digits.length + 1];
withCarry[0] = 1;
return withCarry;
}
}