Problem :

https://leetcode.com/problems/add-two-numbers/description/


My Solution :

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None


class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy_head = ListNode(0)
current = dummy_head
carry = 0
while l1 and l2:
val = (l1.val + l2.val + carry) % 10
carry = (l1.val + l2.val + carry) // 10
current.next = ListNode(val)
current = current.next
l1 = l1.next
l2 = l2.next
remain = l1 or l2
while remain:
val = (remain.val + carry) % 10
carry = (remain.val + carry) // 10
current.next = ListNode(val)
current = current.next
remain = remain.next
if carry:
current.next = ListNode(1)
return dummy_head.next


Comment :

위 코드는 내가 처음으로 시도했던 방법이고, while문을 중복으로 사용하는게 비 효율적이라 판단되어 좀 더 개선된 아래 코드를 만들어 보았다.


My Solution2 :

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None


class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy_head = ListNode(0)
current = dummy_head
carry = 0
while l1 or l2 or carry:
s = carry
if l1:
s += l1.val
l1 = l1.next
if l2:
s += l2.val
l2 = l2.next
current.next = ListNode(s % 10)
current = current.next
carry = s // 10
return dummy_head.next