2. 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.
笔记:
熟悉python的链表的创建与使用
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
num1 = 0
num2 = 0
cnt = 0
while l1:
num1 += l1.val * (10 ** cnt)
cnt += 1
l1 = l1.next
cnt = 0
while l2:
num2 += l2.val *(10 ** cnt)
cnt += 1
l2 = l2.next
rlt = num1 + num2
res = ListNode()
temp_val = rlt % 10
rlt //= 10
res.val = temp_val
temp_list = res
while rlt > 0:
new_list = ListNode()
temp_val = rlt % 10
rlt //= 10
new_list.val = temp_val
temp_list.next = new_list
temp_list = new_list
return res