bigeagle

Untitled

Aug 18th, 2015
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.83 KB | None | 0 0
  1. class Solution:
  2.     # @param {ListNode} l1
  3.     # @param {ListNode} l2
  4.     # @return {ListNode}
  5.     def addTwoNumbers(self, l1, l2):
  6.         from itertools import izip
  7.         def listiter(l):
  8.             cur = l
  9.             while cur:
  10.                 yield (False, cur.val)
  11.                 cur = cur.next
  12.             while 1:
  13.                 yield (True, 0)
  14.                
  15.         head = ListNode(-1)
  16.         cur = head
  17.         carry = 0
  18.         for (e1, x), (e2, y) in izip(listiter(l1), listiter(l2)):
  19.             if e1 and e2:
  20.                 break
  21.             s = x + y + carry
  22.             s, carry = s % 10, s // 10
  23.             node = ListNode(s)
  24.             cur.next = node
  25.             cur = node
  26.         if carry > 0:
  27.             node = ListNode(carry)
  28.             cur.next = node
  29.        
  30.         return head.next
Advertisement
Add Comment
Please, Sign In to add comment