Leetcode 2. Add Two Numbers
Posted pegasus923
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
- https://docs.python.org/3/library/functions.html#divmod
- For integers, the result is the same as
(a // b, a % b)
.
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
以上是关于Leetcode 2. Add Two Numbers的主要内容,如果未能解决你的问题,请参考以下文章
2. 两个数相加 [leetcode 2: Add Two Numbers]
2. 两个数相加 [leetcode 2: Add Two Numbers]