【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)。
解决代码


 class Solution(object):
def plusOne(self, nums):
"""
:type digits: List[int]
:rtype: List[int]
"""
index = len(nums)-1
if not nums:
return []
flow = 0 # 溢出标志量
while index >= 0: # 从尾部开始向前遍历
tem = nums[index] + 1
if tem >= 10: # 如果结果大于等于10的话,设置溢出标志量
flow = 1
nums[index] = tem %10
else: # 否则直接中断
nums[index] = tem %10
flow = 0
break
index -= 1
if flow == 1: # 最后判断溢出是否为1, 因此可能会遇到比如999这种输入。
nums.insert(0, 1) # 在头部插入
return nums
上一篇:彻底修改 Windows 系统用户名


下一篇:SuSe Linux Enterprise Server 10 With Sp2 安装过程图解