링크 : https://leetcode.com/problems/add-two-numbers/
문제 설명
문제
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
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]
Constraints:
- The number of nodes in each linked list is in the range [1, 100].
- 0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros.
문제 풀이
입력 l1, l2는 단일 연결 리스트형태로 제공되어있음.
즉, 연결 리스트를 활용하여 문제를 해결해야 함. (일반 배열로 풀면 안됨)
1. l1, l2의 각 자리를 합 (sum 구하기)
2. 더한 값이 10보다 클 경우 다음 자릿 수에 더해 줘야함 (carry 변수를 활용, Math.floor활용하여 10보다 큰 값 구하기)
3. 10보다 작은 값(digit)를 구하고 새로운 노드의 next 값으로 digit를 생성하여 연결
4. l1, l2의 다음(next)가 있다면 next로 이동
current에 result를 할당하는 것은 result의 head 포인터가 움직이지 않도록 하기 위해(최종결과는 head-> 부터 값을 읽어야 하므로 포인터가 이동하면 안됨. 즉, current를 이용해 포인터를 이동하면서 값을 계산)
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
let result = new ListNode(0);
let current = result;
let carry = 0; // 자리 올림수
while (l1 !== null || l2 !== null || carry !== 0) {
const v1 = l1 ? l1.val : 0;
const v2 = l2 ? l2.val : 0;
const sum = v1 + v2 + carry;
carry = Math.floor(sum / 10);
const digit = sum % 10;
current.next = new ListNode(digit);
current = current.next;
if (l1) {
l1 = l1.next;
}
if (l2) {
l2 = l2.next;
}
}
return result.next;
};
결론
연결 리스트의 .next로 새로운 리스트를 연결하는 과정,
10 초과시 어떻게 처리할지에 대한 부분(carry, digit)을 생각하는게 문제의 핵심같음
'코딩테스트 > LeetCode' 카테고리의 다른 글
| LeetCode 4Sum (JavaScript) (0) | 2025.11.17 |
|---|---|
| LeetCode Letter Combinations of a Phone Number (JavaScript) (0) | 2025.11.17 |
| LeetCode Container With Most Water (JavaScript) (0) | 2025.11.16 |
| LeetCode Zigzag Conversion (JavaScript) (0) | 2025.11.16 |
| LeetCode Longest Palindromic Substring (JavaScript) (0) | 2025.11.16 |