개발/알고리즘
LeetCode 2. Add Two Numbers Python 풀이
Oreorobin
2022. 5. 11. 21:13
LeetCode 2. Add Two Numbers Python
문제
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.
풀이
- 새 연결리스트 now에 l1+l2 를 해줌
- carry 발생 시 다음 num에 +1 넣어줌
소스코드
# 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]:
result = ListNode()
now = result
num = 0
while(True):
if l1:
num += l1.val
# move next node
l1 = l1.next
if l2:
num += l2.val
# move next node
l2 = l2.next
now.val = num % 10
num //= 10
if l1 or l2 or num:
# init & move next node
now.next = ListNode()
now = now.next
else:
break
return result