728x90
반응형
https://leetcode.com/problems/add-two-numbers/description/
문제
문제 분석
- 예시 1과 같이 342 + 465를 계산하는 것이므로 가산기를 구현하였습니다. 역순으로 되어있기에 carry를 그대로 다음 라운드에서 이용할 수 있습니다. 계산 후 값을 결과에 넣을 때만 역순으로 넣어주면 됩니다.
풀이
/**
* 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* dummy = new ListNode();
ListNode* current = dummy;
int carry = 0;
while (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;
current->next = new ListNode(sum % 10);
current = current->next;
}
ListNode* result = dummy->next;
delete dummy;
return result;
}
};
728x90
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
[LeetCode] C++ 328. Odd Even Linked List (0) | 2024.08.17 |
---|---|
[LeetCode] C++ 24. Swap Nodes in Pairs (0) | 2024.08.17 |
[LeetCode] C++ 206. Reverse Linked List (0) | 2024.08.16 |
[LeetCode] C++ 21. Merge Two Sorted Lists (0) | 2024.08.16 |
[LeetCode] C++ 234. Palindrome Linked List (0) | 2024.08.16 |