- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlusOne.java
More file actions
Latest commit
executable file
·27 lines (24 loc) · 818 Bytes
/
Copy pathPlusOne.java
File metadata and controls
executable file
·27 lines (24 loc) · 818 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
/**
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
Hide Tags Array Math
*/
publicclassPlusOne {
publicint[] plusOne(int[] digits) {
if (digits == null || digits.length == 0) returnnull;
intcarry = 1;
for (inti = digits.length - 1; i >= 0; i--) {
if (carry == 0) break;
intsum = carry + digits[i];
digits[i] = sum % 10;
carry = sum / 10;
}
if (carry == 0) returndigits;
int[] res = newint[digits.length + 1];
res[0] = carry;
for (inti = 0; i < digits.length; i++) {
res[i+1] = digits[i];
}
returnres;
}
}