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.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
Constraints:
[1, 100]
.Node.val
<= 9๋ฆฌ์คํธ ํ์ ์ ์ฐ์ฐ ๋ฉ์๋๋ฅผ ์ต๋ํ ํ์ฉํ ๋ฐฉ์์ด๋ค.
# 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: ListNode, l2: ListNode) -> ListNode:
ans1, ans2 = [], []
def dfs(head, ans):
if head == None:
return
ans.append(head.val)
dfs(head.next, ans)
def makeListNode(prev, idx):
if idx == len(ans):
prev.next = None
answer = prev
return
tmp = ListNode(ans[idx])
prev.next = tmp
answer = prev
makeListNode(tmp, idx+1)
dfs(l1, ans1)
dfs(l2, ans2)
ans1.reverse()
ans2.reverse()
ans1 = "".join(list(map(str, ans1)))
ans2 = "".join(list(map(str, ans2)))
ans = list(str(int(ans1) + int(ans2)))
ans.reverse()
head = ListNode(ans[0])
answer = head
makeListNode(head, 1)
return answer
์ด๊ฑด ๋ญ.. ์ฒ์ฐธํ๋ค...
์ฌ๊ท๋ฅผ ๋๋ฆฌ๊ธฐ ๋๋ฌธ์ ๋ฐ๋ณต๋ฌธ์ ๋นํด ์คํ ๊ณต๊ฐ์ ๋ง์ด ์ฐจ์งํ ๊ฑฐ๊ณ + ํ์
๋ณํ์ ์ฌ๋ฌ๋ฒ ํ๋ค๋ณด๋ ๋น์ฐํ ๊ฒฐ๊ณผ๋ค.
carry
๋ฅผ ํ์ฉํด์ ์ด๋ฑ์ํ ๋ง์
์ ๊ตฌํํ๋๊ฒ ์ ํด์๋ค.
์ธ์ฌ์ดํธ๋ฅผ ์ป์์ผ๋ฏ๋ก ๋ค์ ํ์ด๋ณด์.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
answer = ListNode()
head = answer
carry = 0
while l1 or l2 or carry:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
carry, res = divmod(val1 + val2 + carry, 10)
head.next = ListNode(res)
head = head.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return answer.next
๋จ์ํ๊ฒ ์๊ฐํ๋ฉด ์คํ๋ ค ์ฌ์ด ๋ฌธ์ ์๋ค.
๋ฉ์๋๋ฅผ ์๊พธ ์ด์ฉํ๋ ค๊ณ ์๊ฐํ๋ค ๋ณด๋ ๋ถํ์ํ ํ์ ๋ณํ, ์ฌ๊ท ์ฐ์ฐ ๋ฑ๋ฑ์ด ์ถ๊ฐ๋๋ ๊ฒ ๊ฐ๋ค.
์กฐ๊ธ ๋ ์ ์คํ ์๊ฐํด๋ณด๊ณ ํ์ด๋ ๊ด์ฐฎ๋ค.