title: LeetCode 2. Add Two Numbers
level: Medium
Description:
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.
warning >>> status: Runtime Error
# 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:
firstNumber = []
secondNumber = []
while l1 is not None:
firstNumber.append(l1.val)
secondNumber.append(l2.val)
#print(l1.val)
#print(l2.val)
l1 = l1.next
l2 = l2.next
#print(firstNumber)
#print(secondNumber)
firstNumber.reverse()
secondNumber.reverse()
print(firstNumber)
print(secondNumber)
ans = []
inin = 0
for i in range(len(firstNumber)):
tmp = firstNumber[i]+secondNumber[i]
if inin == 1:
tmp = tmp + 1
if tmp < 10:
inin = 0
if tmp >= 10:
inin = 1
tmp = tmp-10
ans.append(tmp)
if inin==1:
ans.append(inin)
print(ans)
#ListNode out
#out = ListNode()
result = ListNode(0)
node = result
for i in range(len(ans)):
node.next = ListNode(ans[i])
node = node.next
return result.next
TODO : Fix it & share how
補(20'09'19): 直接以 link list 理解
# 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:
result = ListNode(0)
node = result
temp = 0
while l1 is not None or l2 is not None or temp>0:
if l1 is not None:
temp += l1.val
l1 = l1.next
if l2 is not None:
temp += l2.val
l2 = l2.next
node.next = ListNode(temp%10) # 取個位數
node = node.next
temp = temp // 10 # 檢查是否要進位
return result.next
ref : 網路