66. plus one

Description

Difficulty: Easy

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

题意:

给一个数组,每个元素表示一个数字的每一位,要求以相同形式给出这个数字加一的结果。

Solution

难点在于进位,特别是由 n 位数变为 n + 1 位数时,如果每一位都移动代价太太。
这里先将数组逆置,然后从头部(即末位)加一,进位完成后在逆置回来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class (object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits_r = digits[::-1]
added = False
for i in xrange(len(digits)):
if digits_r[i] + 1 < 10:
digits_r[i] += 1
added = True
break
elif digits_r[i] + 1 == 10:
digits_r[i] = 0
if added == False:
digits_r.append(1)
return digits_r[::-1]