스터디/기타
[Leetcode] 01. Add Two Numbers (Medium)
훈스비
2022. 2. 19. 16:40

# 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]:
result = ListNode()
curr_node = result
while True:
next_val, curr_node.val = divmod(curr_node.val+l1.val+l2.val, 10)
curr_node.next = ListNode(val=next_val)
if l1.next is None and l2.next is None:
curr_node.next = curr_node.next if next_val != 0 else None
break
l1 = l1.next if l1.next is not None else ListNode()
l2 = l2.next if l2.next is not None else ListNode()
curr_node = curr_node.next
return result
#첫 제출
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
result = ListNode()
curr_node = result
while l1 is not None or l2 is not None:
if l1 is None:
l1 = ListNode()
elif l2 is None:
l2 = ListNode()
next_val, curr_val = divmod(curr_node.val+l1.val+l2.val, 10)
curr_node.val = curr_val
if l1.next is not None or l2.next is not None or next_val != 0:
curr_node.next = ListNode(val=next_val)
l1 = l1.next
l2 = l2.next
curr_node = curr_node.next
return result
https://leetcode.com/problems/add-two-numbers/
Linked list에 역수로 들어가있는 두 숫자를 더하여 반환하는 문제
어떻게 해야 깔끔한 코드가 될 수 있을지 고민하느라 코드를 바꿔봤는데.. 오히려 더 가독성이 떨어진 것 같기도 하다.