์•Œ๊ณ ๋ฆฌ์ฆ˜๐Ÿฅš/๋ฌธ์ œํ’€์ด (Python)

[LeetCode] 2. Add_Two_Numbers (Medium) 2023/5/5

๐Ÿช„ํ•˜๋ฃจ๐Ÿช„ 2023. 5. 5. 17:41
728x90
๋ฌธ์ œ ์ œ๋ชฉ ์ •๋‹ต๋ฅ  ๋‚œ์ด๋„
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โ€‹
728x90