개발/Leetcode
Leetcode 445. Add Two Numbers II
지산동고라니
2023. 7. 17. 12:12
https://leetcode.com/problems/add-two-numbers-ii/description/
Add Two Numbers II - LeetCode
Can you solve this real interview question? Add Two Numbers II - You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers an
leetcode.com
문제
모든 노드가 양수이고 비어있지 않은 LinkedList가 2개 주어진다. 지수가 가장 높은 수 ( 12345 인경우 1)이 제일 먼저 등장하며 그 이후로 그 다음 지수가 높은 수가 등장한다. 이 2개의 LinkedList의 합을 LinkedList로 반환하여라
답을 반환할 때에는 답이 0인 경우를 제외하고 0이 제일 앞에 오는 경우는 0을 포함하지 않고 반환해야 한다.
코드
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
def getNum(ln: ListNode):
a = ''
while ln:
a += str(ln.val)
ln = ln.next
return a
def setNum(n: list):
root = ListNode(int(n.pop()))
cursor = root
while n:
cursor.next = ListNode(n.pop())
cursor = cursor.next
return root
n1 = getNum(l1)
n2 = getNum(l2)
return setNum(list(str(int(n1) + int(n2)))[::-1])
Python이 장점을 활용한 코드, 아무리 큰 수라도 덧셈이 가능한 Python 만만세