source
https://leetcode-cn.com/problems/add-two-numbers/
Title Description
We are given two non-empty list is used to represent two non-negative integer. Where their respective bits are stored in reverse order of the way, 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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Cause: 342 + 465 = 807
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:
n = l1.val + l2.val
l3 = ListNode(n % 10)
l3.next = ListNode(n // 10)
p1 = l1.next
p2 = l2.next
p3 = l3
while True:
if p1 and p2:
total = p1.val + p2.val + p3.next.val
p3.next.val = total % 10
p3.next.next = ListNode(total // 10)
p1 = p1.next
p2 = p2.next
p3 = p3.next
elif p1 and not p2:
total = p1.val + p3.next.val
p3.next.val = total % 10
p3.next.next = ListNode(total // 10)
p1 = p1.next
p3 = p3.next
elif not p1 and p2:
total = p2.val + p3.next.val
p3.next.val = total % 10
p3.next.next = ListNode(total // 10)
p2 = p2.next
p3 = p3.next
else:
if p3.next.val == 0:
p3.next = None
break
return l3
The core idea is to set a new variable l3, to determine whether it is greater than 10, then consider the four cases,
P1 P2同时存在,
P1存在,P2不存在,
P2存在,P1不存在,
P1 P2都不存在
Then after the next node is constantly updated calculated, the final output variable.