본문 바로가기
LeetCode

[LeetCode] 2. Add Two Numbers

by JungSeung 2023. 10. 11.
728x90

https://leetcode.com/

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:

출처 : https://leetcode.com/problems/add-two-numbers/

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.avl <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

 

Code :

var addTwoNumbers = function (l1, l2) {
  // 새로운 연결 리스트의 시작을 나타내는 더미 노드를 생성합니다.
  const node = new ListNode();
  // 임시 노드를 생성하고 더미 노드로 초기화합니다.
  let tmpNode = node;
  // 두 숫자의 합이 10 이상일 때 올림을 나타내는 변수입니다.
  let carry = 0;
  // l1, l2, carry 중 하나라도 값이 존재하는 동안 반복합니다.
  while (l1 || l2 || carry) {
    // 현재 노드의 다음 노드를 생성합니다.
    tmpNode.next = new ListNode();
    // 다음 노드로 이동합니다.
    tmpNode = tmpNode.next;
    // l1, l2의 현재 노드의 값 또는 0(존재하지 않을 경우)을 가져옵니다.
    const left = l1 ? l1.val : 0;
    const right = l2 ? l2.val : 0;
    // 현재 자리의 숫자와 올림을 더합니다.
    let sum = left + right + carry;
    // 현재 자리의 값은 sum이 10 미만일 때는 sum 그대로,
    // 10 이상일 때는 sum을 10으로 나눈 나머지입니다.
    const value = sum < 10 ? sum : sum % 10;
    // 올림은 sum이 10 이상일 때 1, 미만일 때는 0입니다.
    carry = sum < 10 ? 0 : 1;
    // 현재 노드의 값을 계산한 값으로 설정합니다.
    tmpNode.val = value;
    // l1, l2를 다음 노드로 이동합니다.
    l1 = l1 ? l1.next : null;
    l2 = l2 ? l2.next : null;
  }
  // 더미 노드의 다음 노드부터가 실제 결과를 나타내는 연결 리스트입니다.
  return node.next;
};

 

Solutions Code :

var addTwoNumbers = function(l1, l2) {
    const iter = (n1, n2, rest = 0) => {
        // 두 연결 리스트가 끝에 도달하고, 올림 값이 없는 경우 null을 반환합니다.
        if (!n1 && !n2 && !rest) return null;
        // 현재 자리의 숫자를 계산합니다.
        const newVal = (n1?.val || 0) + (n2?.val || 0) + rest;
        // 다음 자리의 노드를 재귀적으로 계산합니다.
        const nextNode = iter(n1?.next, n2?.next, Math.floor(newVal / 10));
        // 현재 노드를 생성하고 반환합니다.
        return new ListNode(newVal % 10, nextNode);
    }
    // 초기 호출로 결과를 반환합니다.
    return iter(l1, l2);
};

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90