作者AmigoSafin ()
看板Python
标题[问题] 新手leecode简单问题一问
时间Sat Jun 1 22:53:28 2019
大家好
超级新手想问问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://webptt.com/cn.aspx?n=bbs/Python/M.1559400811.A.807.html
1F:→ CCWck: 学过资料结构和演算法再来刷题比较好 06/01 23:41
2F:推 XperiaZ6C: 倒数第二行你写成str + int了 06/02 00:12
3F:→ XperiaZ6C: 少看一个括号,没事XD 06/02 00:13
4F:→ XperiaZ6C: 而且你要return的是ListNode,可以试着去修改l1 06/02 00:14
5F:推 art1: 这解法是把链结串列存的值转成字串串接起来,再把字串以相反 06/02 00:43
6F:→ art1: 的顺序读出来并转成整数後相加,相加後的字串再反转一次後存 06/02 00:46
7F:→ art1: 到串列里面,同时也要转成整数,最後缺的就是转成链结串列的 06/02 00:46
8F:→ art1: 格式 06/02 00:47
9F:→ art1: 所以你想办法把这个串列转成题目需要的 ListNode 後回传就行 06/02 00:47
10F:→ AmigoSafin: 谢谢~~我来试试看 06/03 01:14