LeetCode 66 Plus One (Python)

Description

https://leetcode.com/problems/count-and-say/

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.

Solution 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def plusOne(digits):
carry = 1
# range(start, stop, step)
for i in range(len(digits) - 1, -1, -1):

carry = int( digits[i] + carry / 10 )
digits[i] = int( digits[i] + carry % 10 )
if carry == 0:
return digits

result = []
result.append(1)
for i in range(1, len(digits)+1 ):
result.append(digits[i-1])

return result

In python, there are some functions to shorten the code.

  • divmod()

Change:

1
2
carry = int( digits[i] + carry / 10 )
digits[i] = int( digits[i] + carry % 10 )

to:

1
carry, digits[i] = divmod(digits[i] + carry, 10)

divmod(): takes two numbers and returns a pair of numbers consisting of their quotient and remainder, (x / y , x % y)

  • join list
1
2
3
4
5
6
result = []
result.append(1)
for i in range(1, len(digits)+1 ):
result.append(digits[i-1])

return result

to:

1
2
# or: digits.insert(0,1)
return [1] + digits

Solution 2:

1
2
3
4
5
6
7
8
9
def plusOne2(digits):
for i in range(len(digits)-1, -1, -1):
# if the sum is less than 10,than there is not carry
if digits[i] < 9:
digits[i] += 1
return digits
# max: 1+9=10, only 0
digits[i] = 0
return [1] + digits

Exchange blogroll: http://laker.me/blog
Github:https://github.com/younglaker


LeetCode 66 Plus One (Python)

本文原创自http://laker.me/blog,转载请注明出处,欢迎交换友链

如果本文对您有帮助,微信扫一扫,请我吃个鸡腿吧