Game Development
LeetCode 2번 Add Two Numbers 본문

문제 링크
Add Two Numbers - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제
Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
풀이
이 문제는 주어진 단일 연결 리스트에 값들을 더하고 올림이 발생할 경우 다음 위치에 노드에 1을 더해줘야 합니다.
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode* answer = new ListNode();
ListNode* answerBegin = answer;
answerBegin = answer;
int val;
while (l1 != nullptr || l2 != nullptr)
{
val = 0;
if (l1 != nullptr)
{
val += l1->val;
l1 = l1->next;
}
if (l2 != nullptr)
{
val += l2->val;
l2 = l2->next;
}
val += answer->val;
answer->val = val % 10;
if (l1 != nullptr || l2 != nullptr || val >= 10)
{
answer->next = new ListNode(val / 10);
answer = answer->next;
}
}
return answerBegin;
}
};
| Time Submitted | Status | RunTime | Memory |
| 07/25/2021 15:05 | Accepted | 16 ms | 71.3 MB |
시간 복잡도 : O(N)

'Algorithms > Leet Code' 카테고리의 다른 글
| LeetCode 4번 Median of Two Sorted Arrays (0) | 2023.09.23 |
|---|---|
| LeetCode 6번 ZigZag Conversion (0) | 2021.08.04 |
| LeetCode 5번 Longest Palindromic Substring (0) | 2021.07.25 |
| LeetCode 3번 Longest Substring Without Repeating Characters (0) | 2021.07.25 |
| LeetCode 1번 Two Sum (0) | 2021.07.25 |
Comments