2021. 8. 3. 18:15ㆍ노트/Algorithm : 알고리즘
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:
- 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.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def MakeInt(ListNode):
c , num = 0, 0
while ListNode:
v = ListNode.val
ListNode = ListNode.next
num += v * pow(10, c)
c += 1
return num
def MakeLinkedList(num): # 807
head = ListNode(None)
node = head
while True:
v = num % 10 # 7
one = ListNode(v)
node.next = one
node = one
num = num // 10 # 80
if num == 0:
break
return head.next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
num1 , num2 = MakeInt(l1) , MakeInt(l2)
num3 = num1 + num2
solution = MakeLinkedList(num3)
print(solution)
return solution
* 연결 리스트 팁
head 는 None 값을 지정한다 (초기값)
node는 기준이다. 포인터라고 생각하자.
node의 next가 뭐인지 연결하자.
그다음에 node를 기준으로 바꾸자.
연결리스트의 첫번째 값이 일의자리수가 되도록 편하게 문제를 준거다.
% 나머지
// 몫
cf . 54321 숫자에서 5,4,3,2,1 각각 출력하기
num % 10 -> 1
num = num // 10 -> 5432
num % 10 -> 2
num = num // 10 -> 543
num % 10 -> 3
num = num // 10 -> 54
num % 10 -> 4
num = num // 10 -> 5
num % 10 -> 5
num = num // 10 -> 0
'노트 > Algorithm : 알고리즘' 카테고리의 다른 글
[leetcode] 13. Roman to Integer (0) | 2021.08.06 |
---|---|
[leetcode] 1. Two Sum (0) | 2021.08.06 |
[파이썬 알고리즘 인터뷰] 주식을 사고팔기 가장 좋은 시점 (0) | 2021.01.08 |
[파이썬 알고리즘 인터뷰] 자신을 제외한 배열의 곱 (0) | 2021.01.07 |
[파이썬 알고리즘 인터뷰] 배열 파티션 1. (0) | 2021.01.05 |