Subsets II @ LeetCode (Python)
Single Number @ LeetCode (Python)

Add Two Numbers @ LeetCode (Python)

kitt posted @ 2014年2月13日 16:20 in LeetCode , 2659 阅读

 

 

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
 
class Solution:
    # @return a ListNode
    def addTwoNumbers(self, l1, l2):
        carry = 0; head = ListNode(0); curr = head;
        while l1 and l2:
            Sum = l1.val + l2.val + carry
            carry = Sum / 10
            curr.next = ListNode(Sum % 10)
            l1 = l1.next; l2 = l2.next; curr = curr.next
        while l1:
            Sum = l1.val + carry
            carry = Sum / 10
            curr.next = ListNode(Sum % 10)
            l1 = l1.next; curr = curr.next
        while l2:
            Sum = l2.val + carry
            carry = Sum / 10
            curr.next = ListNode(Sum % 10)
            l2 = l2.next; curr = curr.next
        if carry > 0:
            curr.next = ListNode(carry)
        return head.next

# how to test
# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
# Output: 7 -> 0 -> 8
hellohello = Solution()
l1 = ListNode(2)
l1.next = ListNode(4)
l1.next.next = ListNode(3)
l2 = ListNode(5)
l2.next = ListNode(6)
l2.next.next = ListNode(4)
result = hellohello.addTwoNumbers(l1, l2)
p = result
while p:
    print p.val, '->',
    p = p.next
Avatar_small
hello 说:
2015年3月23日 22:45

请问博主,这段代码如何测试呀?l1和l2如何定义?

Avatar_small
kitt 说:
2015年3月24日 03:01

题目给出的啊 @hello:

Avatar_small
hello 说:
2015年3月24日 06:51

@kitt: 不好意思,本人刚学python不久。我是这样验证这段代码的:
a=Solution()
a.addTwoNumbers(l1,l2)
但是l1和l2是什么类型的呢?我试了list类型和元组,都报错。不吝赐教!

Avatar_small
kitt 说:
2015年3月24日 12:00

哦,你是想自己测试一下啊,用type(l1)看类型,我估计是ListNode吧 @hello:

Avatar_small
hello 说:
2015年3月25日 01:50

具体是可以怎么测呢?博主可不可以给个具体例子。多谢!

Avatar_small
围墙内面包 说:
2015年3月26日 10:32

@hello: 你要先定义 ListNode 类啊,然后再实例化 l1 l2

Avatar_small
hello 说:
2015年3月27日 07:47

@围墙内面包: 被注释掉的那个不就是ListNode类吗?我把那段注释取消,然后再怎么定义啊?
不好意思,我比较菜。不知道能否给出具体代码(包括需要调用的main函数)?
感谢回复!

Avatar_small
kitt 说:
2015年4月07日 04:46

请看更新~ @hello:

Avatar_small
hello 说:
2015年4月10日 03:12

感谢!明白了!


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter