문제
https://leetcode.com/problems/add-two-numbers/
Add Two Numbers - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
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.
1. 정수로 이루어져있고, 비어있지 않은 두개의 링크드 리스트가 제공된다.
2. 숫자를 포함하고 있는 각각의 노드는 역순으로 저장되어 있다.
3. 두 정수를 더한 결과를 연결리스트의 형태로 반환하라.
Example 1:
Input | Output |
l1 = [2,4,3], l2 = [5,6,4] | [7,0,8] |
Explanation: 342 + 465 = 807. |
문제풀이 코드
# 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]:
num1 = listNodeToNum(l1)
num2 = listNodeToNum(l2)
values = list(str(num1 + num2))
values.reverse()
lstNode = ListNode(values.pop(0))
for v in values:
lstNode = insertNode(lstNode, v)
return lstNode
def insertNode(curr, val):
if (curr == None):
return ListNode(val)
else:
curr.next = insertNode(curr.next, val)
return curr
def listNodeToNum(listNode):
res = []
while listNode != None:
val = listNode.val
listNode = listNode.next
res.append(str(val))
res.reverse()
return int(''.join(res))
1. Explanation을 보면 l1, l2에 담긴 value들을 뒤집어서 더하고 다시 뒤집으면 정답이 나옴
2. ListNode에 담긴 모든 value들을 꺼내서 뒤집은 값을 주는 함수(listNodeToNum) 생성
3. 결과 값은 ListNode로 보내야 하기 때문에 ListNode에 값을 추가하는 함수(insertNode) 생성
3. l1, l2의 뒤집어진 값을 더한다
4. 더해진 값 리스트로 변환하여 다시 뒤집는다
5. 루프를 돌면서 values에 들어있는 값을 하나씩 ListNode에 추가해준다
'Problem Solving > Leetcode' 카테고리의 다른 글
[Leetcode] 1680. Concatenation of Consecutive Binary Numbers (0) | 2022.09.24 |
---|---|
[Leetcode] 557. Reverse Words in a String III (0) | 2022.09.24 |
[Leetcode] 3. Longest Substring Without Repeating Characters (0) | 2022.09.22 |
[Leetcode] 26. Remove Duplicates from Sorted Array (0) | 2022.09.17 |
[Leetcode] 20. Valid Parentheses (0) | 2022.09.17 |