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.
Solution
(Plus-One.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| public class Solution {
public int[] plusOne(int[] digits) {
int n=digits.length;
for (int i=n-1;i>=0;i--){
if (digits[i]<9){
digits[i]++;
return digits;
}
digits[i] = 0;
}
int[] newdigits = new int[n+1];
newdigits[0] =1;
return newdigits;
}
}
|
(Plus-One.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
n = len(digits)-1
addon = 1
for i in range(n,-1,-1):
newval = digits[i]+addon
digits[i] = newval%10
if newval < 10:
return digits
addon = newval / 10
if addon == 1:
digits.insert(0,1)
return digits
|