bigeagle

Untitled

Aug 18th, 2015
309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 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.         def listiter(l):
  7.             cur = l
  8.             while cur:
  9.                 yield cur.val
  10.                 cur = cur.next
  11.                
  12.                
  13.         ll1 = list(listiter(l1))
  14.         ll2 = list(listiter(l2))
  15.         if len(ll2) < len(ll1):
  16.            ll1, ll2 = ll2, ll1
  17.            
  18.         for _ in range(len(ll2) - len(ll1)):
  19.             ll1.append(0)
  20.        
  21.         head = ListNode(-1)
  22.         cur = head
  23.         carry = 0
  24.         for x, y in zip(ll1, ll2):
  25.             s = x + y + carry
  26.             s, carry = s % 10, s // 10
  27.             node = ListNode(s)
  28.             cur.next = node
  29.             cur = node
  30.         if carry > 0:
  31.             node = ListNode(carry)
  32.             cur.next = node
  33.        
  34.         return head.next
Advertisement
Add Comment
Please, Sign In to add comment