[問題] 新手leecode簡單問題一問

看板Python作者時間5年前 (2019/06/01 22:53), 編輯推噓2(208)
留言10則, 4人參與, 5年前最新討論串1/1
大家好 超級新手想問問leecode一題 已經參考他人solution 但是遇到error: 'int' object is not iterable 想問問怎麼改可以pass呢? 謝謝~~ 題目如下: You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Code如下: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: string_1 = string_2 = '' while l1: string_1 += str(l1.val) l1 = l1.next while l2: string_2 += str(l2.val) l2 = l2.next string_sum = str( int( string_1[::-1] ) + int( string_2[::-1] ) ) return [int(x) for x in string_sum[::-1]] 感謝大家~ solution不是我自己寫的 -- -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 68.180.87.229 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1559400811.A.807.html

06/01 23:41, 5年前 , 1F
學過資料結構和演算法再來刷題比較好
06/01 23:41, 1F

06/02 00:12, 5年前 , 2F
倒數第二行你寫成str + int了
06/02 00:12, 2F

06/02 00:13, 5年前 , 3F
少看一個括號,沒事XD
06/02 00:13, 3F

06/02 00:14, 5年前 , 4F
而且你要return的是ListNode,可以試著去修改l1
06/02 00:14, 4F

06/02 00:43, 5年前 , 5F
這解法是把鏈結串列存的值轉成字串串接起來,再把字串以相反
06/02 00:43, 5F

06/02 00:46, 5年前 , 6F
的順序讀出來並轉成整數後相加,相加後的字串再反轉一次後存
06/02 00:46, 6F

06/02 00:46, 5年前 , 7F
到串列裏面,同時也要轉成整數,最後缺的就是轉成鏈結串列的
06/02 00:46, 7F

06/02 00:47, 5年前 , 8F
格式
06/02 00:47, 8F

06/02 00:47, 5年前 , 9F
所以你想辦法把這個串列轉成題目需要的 ListNode 後回傳就行
06/02 00:47, 9F

06/03 01:14, 5年前 , 10F
謝謝~~我來試試看
06/03 01:14, 10F
文章代碼(AID): #1Syf5hW7 (Python)