-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlusOne.java
More file actions
35 lines (28 loc) · 908 Bytes
/
Copy pathPlusOne.java
File metadata and controls
35 lines (28 loc) · 908 Bytes
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
import java.util.ArrayList;
public class PlusOne {
public static void main(String args[]) {
}
public int[] plusOne(int[] digits) {
ArrayList<Integer> solution = new ArrayList<>();
int carry = 1;
for (int i = digits.length - 1; i >= 0; i--) {
int sum = digits[i] + carry;
if (sum > 9) {
solution.add(0, 0);
} else {
solution.add(0, sum);
carry = 0;
}
}
// If there's still a carry left after the last addition, add it to the front
if (carry != 0) {
solution.add(0, carry);
}
// Convert ArrayList<Integer> to int[]
int[] solutionArray = new int[solution.size()];
for (int i = 0; i < solution.size(); i++) {
solutionArray[i] = solution.get(i);
}
return solutionArray;
}
}