Home Add-two-Numbers
Post
Cancel

Add-two-Numbers

[LeetCode]-02.-Add-two-Numbers

Problem

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.

[해석] 주어진 linked list 2개의 각각의 수를 reverse해서 더한 값을 return 하시오.

example1:

1
2
3
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

example2:

1
2
Input: l1 = [0], l2 = [0]
Output: [0]

example3:

1
2
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

constraints(조건):

  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

[Solution]

이 문제를 풀기 위해 떠오른 방식

  1. 숫자를 거꾸로 정렬해서 합치기
  2. 계산!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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:
        num1 = ''
        num2 = ''

        for n in reversed(l1):
            num1 += str(n)
        
        for m in reversed(l2):
            num2 += str(m)
        
        result = list(str(int(num1) + int(num2)))
        answer = ListNode(result[0], None)

→ 이 방법 사용시 .. listNode는 reversible 하지않다는 errorcode가 뜸

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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:
		num = ''
		num2 = ''

		while l1:
			num1 = str(now.val) + num1
			now = now.next

		while l2: 
			num2 = str(now.val) + num2
			now = now.next

		result = list(str(int(num1) + int(num2)))

		answer = ListNode*result[0], None)

		for i in range(1, len(result)):
			temp = ListNode(result[i], answer)
			answer = temp

		return answer
This post is licensed under CC BY 4.0 by the author.