iT邦幫忙

0

leetcode with python:66. Plus One

題目:

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.

Increment the large integer by one and return the resulting array of digits.

用陣列表示一個數字,一樣用陣列形式回傳該數+1的結果
ex:input: [9]=>output: [1,0]

看似簡單,但要考慮進位的狀況(像上面的範例)

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        digits[-1]=digits[-1]+1
        
        temp=0
        for i in range(1,len(digits)+1):
            digits[-i]=digits[-i]+temp
            if digits[-i]<10:
                temp=0
                break
            temp=digits[-i]//10
            digits[-i]=digits[-i]%10
            
        if temp != 0:
            digits.insert(0,temp)
        return digits

先加一到個位數上,接著從個位開始偵測有沒有進位
有進位就繼續觀測下一位,沒進位就代表上面的值也不會變動了,可以提早結束程式
最後留意最高位是否有進位,有的話就insert進位值到最高位之上
這題reverse後再做應該會比較舒服,不過跟我一樣用負index也行
最後執行時間32ms(faster than 94.21%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言