forked from walnutown/CodingInTheDeep
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlusOne.java
More file actions
26 lines (25 loc) · 1010 Bytes
/
Copy pathPlusOne.java
File metadata and controls
26 lines (25 loc) · 1010 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
/*
Given a number represented as an array of digits, plus one to the number.
*/
// Maintain a varialble to hold the carry
// Traverse from the least significant digit to the most significant digit
// Finally, we have to check 'carry' to know whether we have to resize the array
// One interesting thing is that if we have to resize the array, actually we don't have
// to copy vlaues from original array to new array, because all the values are zero
// time: O(n); space: O(n)
public class Solution {
public int[] plusOne(int[] digits) {
if (digits==null || digits.length==0) return digits;
int carry =1;
for (int i=digits.length-1; i>=0; i--){
int val = digits[i];
digits[i] = (carry+val)%10;
carry = (carry+val)/10;
}
if (carry==0) return digits;
// if we're here, the digits should be 9999..9, and the res is 10000..0
int[] res = new int[digits.length+1];
res[0] =1;
return res;
}
}