066.Plus One

Solution 1: accepted 6%

Brute force with low efficiency.
Q: How to add a new digit at the beginning of an array efficiently?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Solution {
public int[] plusOne(int[] digits) {
int len = digits.length;
int tail = len - 1;
// Increment the last digit
digits[tail]++;
// Check whether digits are carried over
while (digits[tail] > 9 && tail > 0) {
digits[tail] = 0;
digits[tail - 1]++;
tail -= 1;
}
// If the first number is incremented and cause a new digit at the beginning
if (digits[0] > 9) {
digits[0] = 0;
int[] update = new int[len + 1];
update[0] = 1;
for (int i = 1; i < len + 1; i++) {
update[i] = digits[i - 1];
}
return update;
}
return digits;
}
}

Solution 2: accepted

No array manipulation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
public int[] plusOne(int[] digits) {
int len = digits.length;
// If the current digit does not cause a carry, return the updated array immediately
for (int i = len - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
// If the entire array is consisted of "9"s, return a new array leading with a "1" followed by "0"s
int[] update = new int[len + 1];
update[0] = 1;
return update;
}
}