(Medium #2) Add Two Numbers
Problem
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.
My solution
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
l3 = ListNode(0)
print(l1)
l1_val = ''
while l1 != None:
l1_val = str(l1.val) + l1_val
l1 = l1.next
l2_val = ''
while l2 != None:
l2_val = str(l2.val) + l2_val
l2 = l2.next
cal = eval(l1_val + '+' + l2_val)
str_cal = str(cal)
l3_last = ListNode(int(str_cal[0]))
for i in range(1,len(str_cal)):
l3_next = ListNode(int(str_cal[i]))
l3_next.next = l3_last
l3_last = l3_next
print(l3_last)
return l3_last
Other people solution
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(None)
carry = 0
pre = head
while l1 or l2:
curr = ListNode(0)
print(l1.val if l1 else 0)
print(l2.val if l2 else 0)
carry, curr.val = divmod((l1.val if l1 else 0) + (l2.val if l2 else 0) + carry, 10)
pre.next = curr
pre = curr
if l1: l1 = l1.next
if l2: l2 = l2.next
if carry:
pre.next = ListNode(carry)
return head.next
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(None)
carry = 0
pre = head
while l1 or l2:
curr = ListNode(0)
print(l1.val if l1 else 0)
print(l2.val if l2 else 0)
carry, curr.val = divmod((l1.val if l1 else 0) + (l2.val if l2 else 0) + carry, 10)
pre.next = curr
pre = curr
if l1: l1 = l1.next
if l2: l2 = l2.next
if carry:
pre.next = ListNode(carry)
return head.next
댓글
댓글 쓰기