2. The two numbers together
Topic links: https://leetcode-cn.com/problems/add-two-numbers/
Title Description
We are given two non-null linked list is used to represent two non-negative integer. Among them, in accordance with their respective median is the reverse of the way storage, and they each node can store only one digit.
If we add up these two numbers, it will return a new list and to represent them.
You can assume that in addition to the numbers 0, these two numbers will not begin with 0.
Examples
Input : (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output : 7 -> 0 -> 8
Cause : 342 + 465 = 807
Input : (0) + (0)
Output : 0
Reason : 0 + 0 = 0
Input : (9 -> 8) (1) +
Output : 0 -> 9
Cause : 89 + 1 = 90
# 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:
result = ListNode(0)
curr = result
flag = 0
while l1 or l2:
temp1 = 0
temp2 = 0
if l1:
temp1 = l1.val
l1 = l1.next
if l2:
temp2 = l2.val
l2 = l2.next
temp = temp1 + temp2 + flag
curr.next = ListNode(temp%10)
curr = curr.next
flag = temp // 10
if flag != 0:
curr.next = ListNode(1)
return result.next if result.next else result