LeetCode 2. Add Two Numbers
My code seems to be little bit more complex than the solution provided. I feel like I could have done it more efficiently, so the thing I’ve realized is that I need more time and practice to make myself a good thinker.
I’ve struggled because of the following reasons:
It was my first time solving problem on LeetCode. I didn’t know the class ListNode was already implemented in its own system, so I shouldn’t have to implement the new ListNode class, otherwise it will output error messages.
I thought I had to implement all the I/O system by myself, but in Link Node problems, the only thing you need to do is finish the function already provided in the problem and submit the head node of the Link List.
My answer:
# 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: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
ptr_first = ptr_result = ListNode()
flag = 0
first = True
while True:
add = int(l1.val) + int(l2.val) + flag
if first:
ptr = ListNode(add)
first = False
if add > 9:
flag = 1
ptr = ListNode(add - 10)
else:
flag = 0
ptr = ListNode(add)
ptr_result.next = ptr
ptr_result = ptr
l1 = l1.next
l2 = l2.next
if l1 == None and l2 == None and flag == 1:
ptr = ListNode(1)
ptr_result.next = ptr
if l1 == None or l2 == None:
break
# ptr_l2 가 끝났을 때.
while l1 != None:
add = int(l1.val) + flag
if (add > 9):
flag = 1
ptr = ListNode(add - 10)
else:
flag = 0
ptr = ListNode(add)
ptr_result.next = ptr
ptr_result = ptr
l1 = l1.next
if l1 == None and flag == 1:
ptr = ListNode(1)
ptr_result.next = ptr
while l2 != None:
add = int(l2.val) + flag
if (add > 9):
flag = 1
ptr = ListNode(add - 10)
else:
flag = 0
ptr = ListNode(add)
ptr_result.next = ptr
ptr_result = ptr
l2 = l2.next
if l2 == None and flag == 1:
ptr = ListNode(1)
ptr_result.next = ptr
return ptr_first.next
Solution:
class Solution:
def addTwoNumbers(
self, l1: Optional[ListNode], l2: Optional[ListNode]
) -> Optional[ListNode]:
dummyHead = ListNode(0)
curr = dummyHead
carry = 0
while l1 != None or l2 != None or carry != 0:
l1Val = l1.val if l1 else 0
l2Val = l2.val if l2 else 0
columnSum = l1Val + l2Val + carry
carry = columnSum // 10
newNode = ListNode(columnSum % 10)
curr.next = newNode
curr = newNode
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummyHead.next

From the next post, I will be posting about not only the minor things or system problems like I did today but also all the logic I’ve developed while I was solving the problem.