码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode66 Plus One

时间:2020-03-06 13:09:03      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:etc   present   one   mos   for   lse   位置   The   each   

 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

 

leetcode66 Plus One

标签:etc   present   one   mos   for   lse   位置   The   each   

原文地址:https://www.cnblogs.com/yawenw/p/12425680.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!