Leetcode 2. Add Two Numbers

https://leetcode.com/problems/add-two-numbers/

Medium

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
Explanation: 342 + 465 = 807.

  • 注意tricky的地方在于用一个假的头指针,把当前位的和放在next node里,这样就可以避免尾指针为多余0的情况了。
  • divmod(a, b) - Built-in Functions — Python 3.7.4rc2 documentation
 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
 9         dummy_head = ListNode( 0 )
10         p_current = dummy_head
11         carry = 0
12         
13         while l1 or l2:
14             val = carry
15             
16             if l1:
17                 val += l1.val
18                 l1 = l1.next
19             
20             if l2:
21                 val += l2.val
22                 l2 = l2.next
23             
24             # carry, val = divmod( val, 10 )
25             carry = val // 10
26             val = val % 10
27             
28             p_current.next = ListNode( val ) # use next node to store current sum result, otherwise there will be an extra node of 0 on the tail 
29             
30             p_current = p_current.next
31             
32         if carry == 1:
33             p_current.next = ListNode( 1 )
34             
35         return dummy_head.next
View Code

 

posted on 2019-07-08 22:07  浩然119  阅读(110)  评论(0编辑  收藏  举报