728x90
ํํ ๋ฒ์๋ฅผ ๋์ด๊ฐ๋ ์ซ์๊ฐ ์์ด์ ํ ๋นํธ์ฉ ์ฐ์ฐ์ ํด์ค์ผ ํ๋ ๋ฌธ์ . long long์ผ๋ก ํด๋ ์ฒ๋ฆฌ๊ฐ ์๋๋ค.
/**
* 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) {
string list = "";
int carry = 0;
while(l1 != NULL || l2 != NULL) {
int sum = 0;
if(l1 != NULL && l2 != NULL)
sum = l1->val + l2->val + carry;
else if(l1 == NULL && l2 != NULL)
sum = l2->val + carry;
else if(l1 != NULL && l2 == NULL)
sum = l1->val + carry;
if(sum >= 10){
carry = 1;
sum = sum % 10;
} else {
carry = 0;
}
list = list + to_string(sum);
if(l1 != NULL)
l1 = l1->next;
if(l2 != NULL)
l2 = l2->next;
}
if(carry == 1) {
list = list + "1";
}
ListNode* head = new ListNode();
ListNode* answer = head;
for(int i = 0 ; i < list.size() ; i++) {
answer->next = new ListNode();
answer = answer->next;
answer->val = list[i] - '0';
}
return head->next;
}
};
'๐ Self Study > ๐ LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
LeetCode (Two Sum) C++ (0) | 2022.01.07 |
---|---|
LeetCode (Employee Importance) C++ (0) | 2022.01.06 |
LeetCode (Sum of Left Leaves) C++ (0) | 2022.01.06 |