๋ฌธ์ ๋งํฌ : https://leetcode.com/problems/add-two-numbers/description/
ย
๐ฅ๏ธย ์์ํ๋ฉฐ
๋ฌธ์ ์ ์ฃผ์ด์ง ์ํฉ ๊ทธ๋๋ก ํ๋ฉด ๋๋ค.
๊ฐ ๋
ธ๋๋ฅผ ์ํํ๋ฉฐ
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์ ๋ค์ ๋ ธ๋๋ฅผ ๋ฐํ } };
ย
ย
๐ย ์๊ฐ
ย
๐ย ๋ถ๋ก
๐ย ์ฐธ๊ณ ๋ฌธํ
ย
๋๊ธ