forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plus-one.py
38 lines (33 loc) · 842 Bytes
/
plus-one.py
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
32
33
34
35
36
# Time: O(n)
# Space: O(1)
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
for i in reversed(xrange(len(digits))):
if digits[i] == 9:
digits[i] = 0
else:
digits[i] += 1
return digits
digits[0] = 1
digits.append(0)
return digits
# Time: O(n)
# Space: O(n)
class Solution2(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
result = digits[::-1]
carry = 1
for i in xrange(len(result)):
result[i] += carry
carry, result[i] = divmod(result[i], 10)
if carry:
result.append(carry)
return result[::-1]