컴퓨터공학/알고리즘 문제 풀이

[LeetCode] 2. Add Two Numbers

TaeGyeong Lee 2023. 3. 13. 14:56

 

접근

  • 두 노드를 순회하며 계산
  • 친절하게도 이미 거꾸로 뒤업어 놓았음
  • carry 를 활용해서 모든 경우의 수에 부합하는 보편적인 문제 해결 방식을 찾아야

 

솔루션

class Solution:

    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:

        answer = ListNode(0, None)
        answer_cursor = answer
        carry = 0
        
        while l1 != None or l2 != None or carry != 0:
            l1Value = 0
            l2Value = 0
            
            if l1:
                l1Value = l1.val
            if l2:
                l2Value = l2.val
            
            sumOfValue = l1Value + l2Value + carry

            # if carry exist, set carry as 1
            if sumOfValue >= 10:
                carry = 1
            else:
                carry = 0

            # add new node to answer
            node = ListNode(sumOfValue % 10)
            answer_cursor.next = node
            answer_cursor = answer_cursor.next
            
            # go to next
            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next

        return answer.next