-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
31 lines (24 loc) · 887 Bytes
/
Solution.java
File metadata and controls
31 lines (24 loc) · 887 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
public class Solution {
public int[] plusOne(int[] digits) {
if (digits == null)
return null;
if (digits.length == 0)
return new int[]{1};
int idxOfLastElem = digits.length - 1;
int carry = (digits[idxOfLastElem] + 1) / 10;
digits[idxOfLastElem] = (digits[idxOfLastElem] + 1) % 10;
for (int i = digits.length - 2; i >= 0 && carry != 0; i--) {
int sumOfBit = digits[i] + carry;
carry = sumOfBit / 10;
digits[i] = sumOfBit % 10;
}
if (carry == 0) {
return digits;
} else {
int[] result = new int[digits.length + 1];
result[0] = carry;
System.arraycopy(digits, 0, result, 1, digits.length);
return result;
}
}
}