Add two numbers
Difficulty: medium Type: linked list
Two non-empty linked lists are given to represent two non-negative integers. Among them, their respective digits are stored in reverse order, and each of their nodes can only store one digit.
If we add these two numbers together, a new linked list will be returned to represent their sum.
You can assume that except for the number 0, neither of these numbers will start with 0.
Examples
Input: (2-> 4-> 3) + (5-> 6-> 4)
Output: 7-> 0-> 8
Reason: 342 + 465 = 807
Problem-solving ideas
The two lists are traversed at the same time, added bit by bit, and the carry is retained
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode(0) cur = dummy carry = 0 while l1 or l2: num1 = l1.val if l1 else 0 num2 = l2.val if l2 else 0 sum = num1 + num2 + carry carry = sum // 10 cur.next = ListNode(sum%10) cur = cur.next l1 = l1.next if l1 else None l2 = l2.next if l2 else None if carry: cur.next = ListNode(carry) return dummy.next
Author: wzNote
link: https: //www.jianshu.com/p/8ea60c68cde7
Source: Jane books
are copyrighted by the author. For commercial reproduction, please contact the author for authorization, and for non-commercial reproduction, please indicate the source.