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.

O(n) time O(n) space two pass solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
public int[] plusOne(int[] digits) {
int[] res;
int carry = 1;
for (int i = digits.length - 1; i >= 0; i--) {
int sum = digits[i] + carry;
carry = sum / 10;
digits[i] = sum % 10;
}

if (carry == 1) {
res = new int[digits.length + 1];
res[0] = 1;
for (int i = 0; i < digits.length; i++) {
res[i + 1] = digits[i];
}
} else {
res = digits;
}
return res;
}
}

O(n) time O(n) space one pass solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
public int[] plusOne(int[] digits) {
for (int i = digits.length - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i] += 1;
return digits;
} else {
digits[i] = 0;
}
}

if (digits[0] == 0) {
digits = new int[digits.length + 1];
digits[0] = 1;
}
return digits;
}
}