题目原文:
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.
即通过非空数组来表示一个数,数组不会有前导零。对数组表示的数加一,返回对应的数组。
如[1,2]表示12,因此加一得到13,返回[1,3]。
特别地,若有进位发生,[9]加一得到[1,0]。
用python编写代码如下:
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits[-1] += 1
index = -1
while digits[index] == 10:
digits[index] = 0
if -index == len(digits):
digits.insert(0,1)
break
index -= 1
digits[index] += 1
return digits
思路:
从最后一位开始,对列表元素加一,若结果不为10,则返回列表,否则将该元素置为0,并对前一位重复该操作。若当前元素是列表中最后一个元素且结果为10,则在列表首部插入1。