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
'개발 > 알고리즘' 카테고리의 다른 글
프로그래머스 lv3 이중 우선 순위 큐 파이썬 풀이 (0) | 2022.05.25 |
---|---|
Programmers (lv2) 프린터 파이썬(python) 풀이 (0) | 2022.05.18 |
BOJ (1026) - 보물 (0) | 2022.05.04 |
BOJ (1475) - 방 번호 Python (0) | 2021.05.01 |
BOJ (2941) - 크로아티아 알파벳 Python (0) | 2021.05.01 |