- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlusOne.java
More file actions
Latest commit
21 lines (19 loc) · 792 Bytes
/
Copy pathPlusOne.java
File metadata and controls
21 lines (19 loc) · 792 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
publicclassSolution {
publicint[] plusOne(int[] digits) {
intcarry = 1;//The initial one to be added to the array.
for(inti = digits.length - 1; i >= 0; --i){
inttemp = digits[i] + carry;//Add one.
carry = temp / 10;//Do we need to carry the one?
digits[i] = temp % 10;//set new digit.
}
if(carry == 1){// this is in the event that we have to carray a one at the head of the array so we need an array of one size bigger
int[] newArray = newint[digits.length + 1];
newArray[0] = 1;//Set leading digit to one.
for(inti = 0; i < digits.length; i++){
newArray[i+1] = digits[i];
}
returnnewArray;
}
returndigits;
}
}