-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPlusOne.java
More file actions
43 lines (37 loc) · 1.41 KB
/
Copy pathPlusOne.java
File metadata and controls
43 lines (37 loc) · 1.41 KB
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
34
35
36
37
38
39
40
41
42
43
// Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
// See: https://leetcode.com/problems/plus-one/
package leetcode.array_and_hashtable;
import java.util.Arrays;
public class PlusOne {
// TODO: Update with more simple and clear solution
public int[] plusOne(int[] digits) {
if (digits[digits.length - 1] < 9) {
digits[digits.length - 1]++;
return digits;
}
int reminder = 1;
for (int i = digits.length - 1; i >= 0; i--) {
int curr_val = digits[i] + reminder;
if (curr_val == 10) {
reminder = 1;
digits[i] = 0;
} else {
digits[i] = curr_val;
reminder = 0;
}
}
if (reminder == 1) {
digits = new int[digits.length + 1];
digits[0] = 1;
}
return digits;
}
public static void main(String... args) {
PlusOne sln = new PlusOne();
System.out.println(Arrays.toString(sln.plusOne(new int[] {1, 2, 3})));
System.out.println(Arrays.toString(sln.plusOne(new int[] {1, 2, 8})));
System.out.println(Arrays.toString(sln.plusOne(new int[] {1, 2, 9})));
System.out.println(Arrays.toString(sln.plusOne(new int[] {1, 9, 9})));
System.out.println(Arrays.toString(sln.plusOne(new int[] {9, 9, 9})));
}
}