Last active
September 13, 2018 04:01
-
-
Save yokolet/56c4cd255aa33af222d7fa22a9ac4445 to your computer and use it in GitHub Desktop.
Add Two Numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Description: | |
| 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. | |
| Example: | |
| Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) | |
| Output: 7 -> 0 -> 8 --- 342 + 465 = 807 | |
| """ | |
| class ListNode: | |
| def __init__(self, x): | |
| self.val = x | |
| self.next = None | |
| def addTwoNumbers(l1, l2): | |
| """ | |
| :type l1: ListNode | |
| :type l2: ListNode | |
| :rtype: ListNode | |
| """ | |
| if not l1 or not l2: | |
| return l1 or l2 | |
| head = l1 | |
| carry = 0 | |
| while l1 and l2: | |
| carry, rem = divmod(l1.val + l2.val + carry, 10) | |
| l1.val = rem | |
| cur, l1, l2 = l1, l1.next, l2.next | |
| cur.next = l1 or l2 | |
| print('carry', carry) | |
| while carry != 0: | |
| if not cur.next: | |
| cur.next = ListNode(carry) | |
| break | |
| else: | |
| carry, rem = divmod(cur.next.val + carry, 10) | |
| cur.next.val = rem | |
| cur = cur.next | |
| return head |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment