码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 2. Add Two Numbers

时间:2019-07-08 22:24:14      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:gif   css   res   sed   output   Plan   example   inpu   mtd   

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

 

Leetcode 2. Add Two Numbers

标签:gif   css   res   sed   output   Plan   example   inpu   mtd   

原文地址:https://www.cnblogs.com/pegasus923/p/11154158.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!