Development/Algorithm

[LeetCode] Add Two Numbers

동스토리 2021. 8. 4. 10:33
반응형

안녕하세요.

 

LeetCode 2번 Add Two Number 문제풀이 하겠습니다.

 

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

 

[문제]

 

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

 

[TestCase]

 

[해설]

 

해당 문제는 2->4->3 즉, 342 + 5->6->4 즉, 465

  = 807 즉, 7->0->8 을 반환해야 합니다.

 

carry를 0으로 초기화 후

두개의 Linekd List L1, L2에 carry를 더해

 10으로 나눈 나머지 값은 next 노드에

10으로 나눈 몫은 carry에 저장하는 것을 반복하여 값을 구한다.

 

[코드]

 

# 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: ListNode, l2: ListNode) -> ListNode:
        result = head = ListNode()

        carry =0

        while l1 or l2 or carry:
            l1_val = 0
            l2_val = 0
            if l1:
                l1_val = l1.val
                l1 = l1.next
            if l2:
                l2_val = l2.val
                l2 = l2.next

            sum = (l1_val + l2_val + carry)

            new_val = sum % 10
            carry = sum // 10
            head.next = ListNode(new_val)
            head = head.next

        return result.next

 

감사합니다.

반응형