-
Leetcode 445. Add Two Numbers II개발/Leetcode 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.nextreturn a
def setNum(n: list):root = ListNode(int(n.pop()))cursor = rootwhile n:cursor.next = ListNode(n.pop())cursor = cursor.next
return rootn1 = getNum(l1)n2 = getNum(l2)
return setNum(list(str(int(n1) + int(n2)))[::-1])
Python이 장점을 활용한 코드, 아무리 큰 수라도 덧셈이 가능한 Python 만만세
'개발 > Leetcode' 카테고리의 다른 글
Leetcode 435. Non-overlapping Intervals (0) 2023.07.19 Leetcode 146. LRU Cache (0) 2023.07.18 Leetcode 1125. Smallest Sufficient Team (0) 2023.07.16 Leetcode 1751. Maximum Number of Events That Can Be Attended II (0) 2023.07.15 Leetcode 1218. Longest Arithmetic Subsequence of Given Difference (0) 2023.07.14