iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 6
0
自我挑戰組

Leetcode新手挑戰30天系列 第 6

#66 Plus One

寫在開頭

昨天回文那題自己覺得解的有點困難,想找一題看起來簡單些的題目來練習,希望可以增加一點信心吧(哭笑)

開始寫題

第66題Plus One題目如下:

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.

這題開頭說Input一定是正整數、按照位數顯示的陣列,要把這個數字加1
我想到的方法有兩種:
1.把輸入的列表先轉成數字,加1後再轉回輸出結果的列表
2.取出陣列最尾的元素加1
不過2的方法要多判斷是否需要進位的狀況

這題我想用我想到的方法2先來試著解看看

def plusOne(self, digits: List[int]) -> List[int]:
    digits[len(digits)-1] = digits[len(digits)-1] + 1
    i = 1
    while digits[len(digits)-i] > 9:
        if i > len(digits):
            digits.insert(0, 1)
        digits[len(digits)-i] = digits[len(digits)-i] - 10
        digits[len(digits)-(i+1)] = digits[len(digits)-(i+1)] + 1
        i = i + 1
    return digits

第一次的code長這樣,先把最尾位數的數字加1後放回,然後判斷是否欄位大於9需要做進位處理
如果原本2位長要進位變成3位長的話,我想到用list.insert()新增第0位的資料上去
但實際在跑測試個案時,如果是Input=99的測試個案會出錯
Input=[9,9]
Output=[0,1]
Expected=[1,0,0]

因為今天寫的時間有點晚, 決定明天在想錯誤原因


上一篇
#9 Palindrome Number - 研究其他種解法
下一篇
#66 Plus One - 繼續解
系列文
Leetcode新手挑戰30天31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言