-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPlusOne.java
41 lines (35 loc) · 973 Bytes
/
PlusOne.java
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
package com.smlnskgmail.jaman.leetcodejava.easy;
import java.util.Arrays;
// https://leetcode.com/problems/plus-one/submissions/
public class PlusOne {
private final int[] input;
public PlusOne(int[] input) {
this.input = input;
}
public int[] solution() {
boolean overflow = false;
for (int i = input.length - 1; i >= 0; i--) {
int digit = input[i] + 1;
overflow = digit >= 10;
if (overflow) {
input[i] = 0;
} else {
input[i] = digit;
break;
}
}
if (overflow) {
int[] result = Arrays.copyOf(input, input.length + 1);
result[0] = 1;
System.arraycopy(
input,
0,
result,
1,
input.length
);
return result;
}
return input;
}
}