leetcode 【 Plus One 】python 实现
题目: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.
代码:oj测试通过 Runtime: 47 ms
1 class Solution:
2 # @param digits, a list of integer digits
3 # @return a list of integer digits
4 def plusOne(self, digits):
5 if digits is None:
6 return None
7 if len(digits) == 0 :
8 return digits
9 length = len(digits)
10 new_last_digit = digits + 1
11 if new_last_digit / 10 == 0:
12 digits = new_last_digit
13 return digits
14 else:
15 jinwei = 1
16 digits = 0
17 for i in range(length-2,-1,-1):
18 curr_value = jinwei + digits
19 if curr_value/10 == 0:
20 digits = curr_value
21 return digits
22 else:
23 digits = curr_value % 10
24 digits.insert(0,1)
25 return digits
思路:
先排除special case
然后就逐渐往前加,维护一个jinwei变量
注意 如果最后有进位 需要在数组开头再补充一个1 这里用到了insert函数 之前还不知道python数组有这个函数
页:
[1]