066. Plus One

Question 066

https://leetcode.com/problems/plus-one/description/

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.

for example input:[1,2,3,4] >> output:[1,2,3,5] input:[1,3,0,0,9] >> output[1,3,0,1,0] input:[0] >> output:[1]

Answer

v1. switch to int first

  1. 利用迴圈將 List 的位數依序乘上 10

  2. 將得出的整數 +1

  3. 將整數除以 10 取餘數,並塞入新的 List 中

  4. 將 List 以 .reverse() 反轉 ps. reverse() 並不會回傳值,而是直接對 List 本身做處理

v2. use regression

  1. 如果最後一位數小於 9 , 只需將最後一位數 +1 。

  2. 如果最後一位數為 9 , 便需要做進位處理。

要在 function 裡呼叫自己本身的所在的 function ==> self.FunctionName()

import math

class Solution(object):
    def plusOne(self, digits):
    
        AnsInt = 0
        Answer = []
    
        # switch to int
        for digit in digits:
            AnsInt = int(digit) + 10*AnsInt
        
        # plus one to int
        AnsInt += 1
        
        # switch back to List
        while AnsInt > 0 :
            Append_Temp = AnsInt % 10
            Answer.append(Append_Temp)
            AnsInt = AnsInt/10
        
        # The answer
        Answer.reverse()
        return Answer

welcome to check my Github LeetCode-share(https://github.com/QuenLo/LeeCode-share)

Last updated