Skip to content

Commit 9f3cc42

Browse files
committed
66. plus one
1 parent 102fc33 commit 9f3cc42

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

66PlusOne/PlusOne.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @author jiofeng
3+
* @date 2020/3/1
4+
*/
5+
public class PlusOne {
6+
public static void main(String[] args) {
7+
int[] digits = {9, 8, 9};
8+
for (int digit : new PlusOneSolution().plusOne(digits)) {
9+
System.out.println(digit);
10+
}
11+
}
12+
}
13+
14+
class PlusOneSolution {
15+
public int[] plusOne(int[] digits) {
16+
boolean carryFlag = true;
17+
for (int i = digits.length - 1; i >= 0; i--) {
18+
if (carryFlag) {
19+
digits[i] = ++digits[i];
20+
carryFlag = false;
21+
}
22+
if (digits[i] >= 10) {
23+
digits[i] %= 10;
24+
carryFlag = true;
25+
}
26+
if (!carryFlag) {
27+
break;
28+
}
29+
}
30+
if (carryFlag) {
31+
int[] newDigits = new int[digits.length + 1];
32+
newDigits[0] = 1;
33+
return newDigits;
34+
}
35+
return digits;
36+
}
37+
}

0 commit comments

Comments
 (0)