leetcode_plus one

Plus One

Given a non-empty array of digits representing a non-negative integer, plus one to the integer. The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself.
(数组形式的数字串数值加1)

Example:

1. 加法进位原则

Note: 需要特别注意第一个数字进位的情况。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class :
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""

n = len(digits)

add = 1
result = [0 for _ in range(n+1)]

for i in range(n-1, -1, -1):
add += digits[i]
result[i+1] = add % 10
add = add // 10

if add == 0:
return result[1:]
else:
result[0] = add
return result