๋ฌธ์ ์ ๋ชฉ | ์ ๋ต๋ฅ | ๋์ด๋ |
2. Add-Two-Numbers | 40.5% | Medium |
Add Two Numbers - LeetCode
Can you solve this real interview question? Add Two Numbers - 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
leetcode.com
๋ฌธ์ ์์ฝ
์ญ์์ผ๋ก ์ ์ฅ๋ ์ฐ๊ฒฐ๋ฆฌ์คํธ์ ํฉ์ ๊ตฌํ์ฌ๋ผ
์กฐ๊ฑด 1) ๋ ๊ฐ์ ์ฐ๊ฒฐ๋ฆฌ์คํธ์ ๊ธธ์ด๋ 1 ์ด์ 100 ์ดํ์ด๋ค
์กฐ๊ฑด 2) ์ฐ๊ฒฐ๋ฆฌ์คํธ ๊ฐ ๋ ธ๋๋ ํ์๋ฆฌ์ ์์๊ฐ ์๋ ์ซ์๊ฐ ์ ์ฅ๋์ด ์๋ค (0~9)
์กฐ๊ฑด 3) ํฉ์ณ์ง ํ๋์ ์ ๋ ฌ๋ ์ฐ๊ฒฐ๋ฆฌ์คํธ์ ํค๋๋ฅผ ๋ฐํํด์ผ ํ๋ค
ํ์ด 1
๋ ๋ ธ๋๋ฅผ ์ด๋ํ๋ฉฐ ์์ฐจ์ ์ผ๋ก ๋ง์ ์ฐ์ฐ ์ํ
Step1. ๋น ๋ ธ๋ ์ ์ธ
Step2. ๋ ์ฐ๊ฒฐ๋ฆฌ์คํธ ๋ง์ ์ฐ์ฐ ์ํ
๋ ์ฐ๊ฒฐ๋ฆฌ์คํธ ๋ชจ๋ ๋น ๊ฐ์ ๊ฐ๋ฆฌํค๊ธฐ ์ ๊น์ง
ํด๋น ์ฐ๊ฒฐ๋ฆฌ์คํธ์ ๊ฐ์ ๋ํ ๋ค, 10 ์ดํ๋ ์ ์ฅํ๊ณ ๋๋จธ์ง ๊ฐ์ ๊ทธ ์ดํ ์ฐ์ฐ์์ ์ฒ๋ฆฌ
- upper%10 ์ ์ฅ
- upper//10 ๋ค์ ์ฐ์ฐ์์ ์ฒ๋ฆฌ
Step3. ์ฐ๊ฒฐ๋ฆฌ์คํธ์ head ๋ถ๋ถ์ ๋น ์ฐ๊ฒฐ๋ฆฌ์คํธ๋ฅผ ์ ์ธํ์ผ๋ฏ๋ก ๋ค์ ๋ ธ๋ ์ฃผ์๋ฅผ ๋ฐํ
๊ตฌํ
# 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]:
pointer1=l1
pointer2=l2
# Step 0
head=prev=ListNode(0)
# Step 1
upper=0
while not(pointer1==None and pointer2==None) or upper:
plus=upper%10
if pointer1!=None:
plus+=pointer1.val
pointer1=pointer1.next
if pointer2!=None:
plus+=pointer2.val
pointer2=pointer2.next
prev.next=ListNode(plus%10, None)
prev=prev.next
upper=plus//10
# Step 3
return head.nextโ
'์๊ณ ๋ฆฌ์ฆ๐ฅ > ๋ฌธ์ ํ์ด (Python)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 316. remove_duplicate_letters (Medium) 2023/5/8 (0) | 2023.05.08 |
---|---|
[LeetCode] 20. Valid_Parentheses (Easy) 2023/5/8 (0) | 2023.05.08 |
[LeetCode] 206. Reverse_Linked_List (Easy) 2023/5/5 (0) | 2023.05.05 |
[LeetCode] 21. Merge_Two_Sorted_Lists (Easy) 2023/5/5 (0) | 2023.05.05 |
[LeetCode] 234. Palindrome_Linked_list (Easy) 2023/5/4 (0) | 2023.05.04 |