LeetCode/Top Interview 150

2. Add Two Numbers

hyunkookim 2024. 12. 7. 16:48

2. Add Two Numbers

 

https://youtu.be/wgFPrzTjm7s?si=DGP0R4iCDigdI7GY

 

https://youtu.be/oRVhdwpTbdU?si=SVZBd8Gq4JuCsoDP

 

# 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]:
        # The digits are stored in reverse order: 역순으로 저장되어 있다.
        # 링크드리스트를 순회하면서 값 더하면 됨
        
        dummy = ListNode()
        cur = dummy

        carry = 0 # 두개 더했을때, 10의 자리 수, 올림수
        
        while l1 or l2 or carry: # carry 가 0이 아니면, 추가해야하므로, 아주 중요!!
            v1 = l1.val if l1 else 0
            v2 = l2.val if l2 else 0

            # new digit
            val = v1 + v2 + carry
            
            # 15
            carry = val // 10
            val = val % 10
            cur.next = ListNode(val)

            # update pointers
            cur = cur.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        
        return dummy.next

 

 

# dummy 노드를 만들어서, 처리하고, dummy->next 를 반환하면 됨. **숙지하자**

'LeetCode > Top Interview 150' 카테고리의 다른 글

138. Copy List with Random Pointer  (0) 2024.12.07
21. Merge Two Sorted Lists  (0) 2024.12.07
List(싸이클탐지): 141. Linked List Cycle  (0) 2024.12.06
224. Basic Calculator  (0) 2024.12.06
150. Evaluate Reverse Polish Notation  (0) 2024.12.06