leetcode66 Plus One

 1 """
 2 Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
 3 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.
 4 You may assume the integer does not contain any leading zero, except the number 0 itself.
 5 Example 1:
 6 Input: [1,2,3]
 7 Output: [1,2,4]
 8 Explanation: The array represents the integer 123.
 9 Example 2:
10 Input: [4,3,2,1]
11 Output: [4,3,2,2]
12 Explanation: The array represents the integer 4321.
13 """
14 """
15 解法一:从后向前迭代。当迭代到最高位时如果要进位
16 需要再次判断,运用了insert(a, b)函数。表示在位置a前插入b元素
17 """
18 class Solution1:
19     def plusOne(self, digits):
20         carry = 0
21         digits[len(digits)-1] += 1
22         for i in range(len(digits)-1, -1, -1):
23             if digits[i]+carry == 10:
24                 digits[i] = 0
25                 carry = 1
26                 if i == 0:
27                     digits.insert(i, 1)
28             else:
29                 digits[i] += carry
30                 carry = 0
31         return digits
32 """
33 解法二:递归
34 """
35 class Solution2:
36     def plusOne(self, digits):
37         if len(digits) == 1 and digits[0] == 9:
38             return [1, 0]
39         if digits[-1] != 9:
40             digits[-1] += 1
41             return digits
42         else:
43             digits[-1] = 0
44             digits[:-1] = self.plusOne(digits[:-1])
45         return digits

 

posted @ 2020-03-06 11:45  yawenw  阅读(148)  评论(0编辑  收藏  举报