[LeetCode]#66. Plus One

Fatboy Slim
2 min readApr 8, 2020

--

Environment: Python 3.7

Key technique: Counter, slice

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.

Analysis:

  1. Covert is to string.
  2. Covert it to int and +1
  3. Use slice to back it to list
  4. Special case [9]: Due to 9+1=10 and output is [1,0]. We can see list size is bigger than original one.
  5. Use Counter to calculate how many 9 and calculate list size.
  6. If they are the same, output list size +1

Solution:

from collections import Counter
class Solution:
def plusOne(self, digits):
d_str, l, ans, move ="", len(digits), [],0
nine=Counter(digits)
if nine[9]==l:
move=1
for i in range(l):
d_str=d_str+str(digits[i])
add=int(d_str)+1
b=str(add)
for i in range(0,l+move):
ans.append(int(b[i:i+1]))
return ans

Submitted result:

Lesson learn:

Carry issue let me take many time debug.

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet