LeetCode Add Two Numbers (JavaScript)

2025. 11. 16. 16:47·코딩테스트/LeetCode

링크 : 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
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Letter Combinations of a Phone Number (JavaScript)
  • LeetCode Container With Most Water (JavaScript)
  • LeetCode Zigzag Conversion (JavaScript)
  • LeetCode Longest Palindromic Substring (JavaScript)
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (211) N
      • 프론트엔드 (64) N
        • JavaScript (51)
        • HTML (3)
        • React (7) N
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (125) N
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (36) N
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Add Two Numbers (JavaScript)
상단으로

티스토리툴바