[Leetcode] 2. Add Two Numbers
[Leetcode] 2. Add Two Numbers

[Leetcode] 2. Add Two Numbers

์–ธ์–ด
Python
C
๋‚œ์ด๋„
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜ ์œ ํ˜•
์ž‘์„ฑ์ž
๋ฐ•์šฉ์„ฑ๋ฐ•์šฉ์„ฑ
์ƒ์„ฑ ์ผ์‹œ
2024๋…„ 06์›” 02์ผ
ย 

๐Ÿ–ฅ๏ธย ์‹œ์ž‘ํ•˜๋ฉฐ

๋ฌธ์ œ์— ์ฃผ์–ด์ง„ ์ƒํ™ฉ ๊ทธ๋Œ€๋กœ ํ’€๋ฉด ๋œ๋‹ค.
๊ฐ ๋…ธ๋“œ๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ val ๊ฐ’์„ ๋”ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.
ย 

โš™๏ธย Python

from typing import Optional 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]: res = ListNode(0) # ๋”๋ฏธ ๋…ธ๋“œ cur = res carry = 0 while ( l1 or l2 or carry ): # l1, l2 ๋‘˜ ์ค‘ ํ•˜๋‚˜๋ผ๋„ ๋‚จ์•„ ์žˆ๊ฑฐ๋‚˜, carry๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ ๊ณ„์† ์‹คํ–‰ sum = carry if l1: sum += l1.val l1 = l1.next if l2: sum += l2.val l2 = l2.next carry = sum // 10 cur.next = ListNode(sum % 10) cur = cur.next return res.next s = Solution() print(s.addTwoNumbers(l1=[2, 4, 3], l2=[5, 6, 4]))

โš™๏ธย C++

#include <vector> using namespace std; // Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode *res = new ListNode(0); ListNode *cur = res; int carry = 0; while (l1 || l2 || carry) { // l1, l2 ๋˜๋Š” carry ์ค‘ ํ•˜๋‚˜๋ผ๋„ ์žˆ๋Š” ๊ฒฝ์šฐ ๊ณ„์† ์‹คํ–‰ int sum = carry; if (l1) { sum += l1->val; l1 = l1->next; } if (l2) { sum += l2->val; l2 = l2->next; } carry = sum / 10; cur->next = new ListNode(sum % 10); cur = cur->next; } return res->next; // dummy node์˜ ๋‹ค์Œ ๋…ธ๋“œ๋ฅผ ๋ฐ˜ํ™˜ } };
ย 
ย 

๐Ÿ“Œย ์†Œ๊ฐ

ย 

๐Ÿ”ย ๋ถ€๋ก

๐Ÿ”ย ์ฐธ๊ณ ๋ฌธํ—Œ


ย 

๋Œ“๊ธ€

guest