[알고리즘] Leetcode Add two Numbers

진실·2022년 11월 21일
0

알고리즘

목록 보기
13/22
post-custom-banner

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

# 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]:
        head = l3 = ListNode(0)
        carry = False
        
        
        while l1 or l2 or carry: 
            cur = 0
            
            if l1 : 
                cur += l1.val
                l1 = l1.next
            if l2 : 
                cur += l2.val
                l2 = l2.next
            
            if carry : 
                cur += 1
            
            if cur >= 10 : 
                carry = True
                cur -= 10
            else : 
                carry = False
            
            
            l3.next = ListNode(cur)
            l3 = l3.next
        
        return head.next
                
profile
반갑습니다.
post-custom-banner

0개의 댓글