【LeetCode每天一题】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.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

思路

  这道题在python中还是挺好解决的, 直接从列表的尾部开始进行并设置一个溢出标志量,然后执行加法操作,如果加之后的结果小于10的话,直接中断,并判断溢出标志量。否则指针减1,开始新一轮的计算。直到遍历到头部结束。时间复杂度为O(n), 空间复杂度为O(1)。
解决代码


 1 class Solution(object):
 2     def plusOne(self, nums):
 3         """
 4         :type digits: List[int]
 5         :rtype: List[int]
 6         """
 7         index = len(nums)-1
 8         if not nums:
 9             return []
10         flow = 0          # 溢出标志量
11         while index >= 0:    # 从尾部开始向前遍历
12             tem = nums[index] + 1
13             if tem >= 10:     # 如果结果大于等于10的话,设置溢出标志量
14                 flow = 1
15                 nums[index] = tem %10
16             else:                # 否则直接中断
17                 nums[index] = tem %10
18                 flow = 0
19                 break
20             index -= 1
21         if flow == 1:          # 最后判断溢出是否为1, 因此可能会遇到比如999这种输入。
22             nums.insert(0, 1)     # 在头部插入
23         return nums            
posted @ 2019-04-24 17:08  GoodRnne  阅读(218)  评论(0编辑  收藏  举报