본문 바로가기
Programming/LeetCode

[LeetCode] Add Two Numbers

by 데이터현 2022. 3. 23.

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

 

Add Two Numbers - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

연결 리스트를 뒤집어서 더한 값을 다시 뒤집어서 반환

내 풀이

# 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]:
        first = second = ''
        answer = ListNode()
        head = answer
        while l1 or l2:
            if l1:
                first += str(l1.val)
                l1 = l1.next
            if l2:
                second += str(l2.val)
                l2 = l2.next
        for i in str(int(first[::-1]) + int(second[::-1]))[::-1]:
            head.next = ListNode(val=int(i))
            head = head.next
        return answer.next

 

 

가독성도 안 좋고 형 변환이 많아서 속도도 안 나온다.

 

전가산기 구현

# 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]:
        root = head = ListNode(0)
        carry = 0
        
        while l1 or l2 or carry:
            sum = 0
            if l1:
                sum += l1.val
                l1 = l1.next
            if l2:
                sum += l2.val
                l2 = l2.next
            carry, val = divmod(carry + sum, 10)
            head.next = ListNode(val)
            head = head.next
        return root.next

깔--끔

'Programming > LeetCode' 카테고리의 다른 글

[LeetCode] Swap Nodes in Pairs  (0) 2022.03.24
[LeetCode] Boats to Save People  (0) 2022.03.24
[LeetCode] Reverse Linked List  (0) 2022.03.23
[LeetCode] Broken Calculator  (0) 2022.03.23
[LeetCode] Merge Two Sorted Lists  (0) 2022.03.23

댓글