# 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에 역수로 들어가있는 두 숫자를 더하여 반환하는 문제
어떻게 해야 깔끔한 코드가 될 수 있을지 고민하느라 코드를 바꿔봤는데.. 오히려 더 가독성이 떨어진 것 같기도 하다.
'스터디 > 기타' 카테고리의 다른 글
[Linux] Udemy - Linux Command Line 부트캠프 강의 후기 (0) | 2024.04.28 |
---|---|
[Ray] 1. Python - Ray의 기본 개념과 Tasks (2) | 2021.03.12 |
[Ray] 0. GCP와 Docker를 이용한 Jupyter Notebook 환경 구성 (0) | 2021.03.07 |
[Open API] 사이퍼즈 전적 검색 사이트 만들기 #1 - 닉네임 검색 (1) | 2019.08.04 |
[프로세스 마이닝] Data Science In Action 강의 - 02 (0) | 2019.08.03 |