[LeetCode] Add Two Numbers

피누·2020년 9월 20일
0

Descirption

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 contain a single digit. Add the two numbers and return it as a linked list.

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

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Code

# 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:
        """
        1. create new linked list for return
        2. 짧은 노드 기준으로 루프 돌면서 +
        """
        start_node = ListNode()
        current_node = start_node
        carry = 0
        
        while l1 and l2:
            sum_value = l1.val + l2.val
            rest = (sum_value + carry) % 10
            current_node.next = ListNode(val=rest)
            
            carry = int((sum_value + carry) / 10)
            l1 = l1.next
            l2 = l2.next
            current_node = current_node.next
        
        
        while l1:
            rest = (l1.val + carry) % 10
            current_node.next = ListNode(val=rest)
            
            carry = int((l1.val + carry) / 10)
            l1 = l1.next
            current_node = current_node.next
            
        while l2:
            rest = (l2.val + carry) % 10
            current_node.next = ListNode(val=rest)
            
            carry = int((l2.val + carry) / 10)
            l2 = l2.next
            current_node = current_node.next
            
        if carry == 1:
            current_node.next = ListNode(val=1)
        
        
        return start_node.next

999 + 1 인 경우에는 캐리가 연쇄적으로 올라가기 때문에, 루프가 끝난 후에도 캐리값이 남아있는지 검사해야한다.

profile
어려운 문제를 함께 풀어가는 것을 좋아합니다.

0개의 댓글