【英文】加一

Preface

LeetCode Answer, Java language

Problem

Source Code

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
class Solution {
public int[] plusOne(int[] digits) {

// Expand the given array
int[] arr = new int[digits.length+1];
for (int j = digits.length-1; j >= 0; j--) {
arr[j+1] = digits[j];
}

// Algorithm: Add one when it hits ten
for (int k = arr.length-1; k >= 0 ; k--) {
arr[k]++;
if (arr[k]==10) {
arr[k] = 0;
continue;
}
break;
}

// If the new array starts with `0` (meaning that the expansion is useless), perform a reduction operation
if (arr[0]==0) {
int[] arr2 = new int[arr.length-1];

for (int n = arr2.length-1; n >= 0; n--) {
arr2[n] = arr[n+1];
}
return arr2;
}

return arr;
}

}

Completion