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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
现在做题不仅要ac,还要找到比较高效的做法。这道题目是两个链表相加,很容易想到边界条件,不过我开始的代码写的有些臃肿,而且变量名也很中式。代码如下:
class ListNode(object): def __init__(self, x): self.val = x self.next = Noneclass Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ p = ListNode(0) ans = p jinwei = 0 while l1 and l2: jieguo = (l1.val + l2.val + jinwei) % 10 jinwei = (l1.val + l2.val + jinwei) / 10 p.val = jieguo l1 = l1.next l2 = l2.next if l1 and l2: p.next = ListNode(0) p = p.next if l1 and not l2: while l1: jieguo = (l1.val + jinwei) % 10 jinwei = (l1.val + jinwei) / 10 p.next = ListNode(jieguo) p = p.next l1 = l1.next if l2 and not l1: while l2: jieguo = (l2.val + jinwei) % 10 jinwei = (l2.val + jinwei) / 10 p.next = ListNode(jieguo) p = p.next l2 = l2.next if jinwei > 0: p.next = ListNode(0) p.next.val = jinwei return ansif __name__ == '__main__': n0 = ListNode(2) n1 = ListNode(4) n2 = ListNode(3) n3 = ListNode(5) n4 = ListNode(6) n5 = ListNode(4) n0.next = n1 n1.next = n2 n3.next = n4 n4.next = n5 s = Solution() ans = s.addTwoNumbers(n0, n3) while ans: print ans.val ans = ans.next
可以看到有很多重复的代码,运行起来并不高效。
来看下面的代码,进位英文是carry
class ListNode(object): def __init__(self, x): self.val = x self.next = Noneclass Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ pHead = ListNode(0) cur = pHead carry = 0 total = 0 while l1 or l2: x = l1.val if l1 else 0 y = l2.val if l2 else 0 total = x + y + carry carry = total / 10 cur.next = ListNode(total % 10) cur = cur.next if l1: l1 = l1.next if l2: l2 = l2.next if carry > 0: cur.next = ListNode(carry) return pHead.next