LeetCode

[리트코드] 2. Add Two Numbers / Javascript

개발하는 사막여우 2021. 9. 9. 17:36
반응형

문제주소 :https://leetcode.com/problems/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


<문제 설명>

더보기

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.

 

<풀이법>

▒ 한줄 개념: 연결리스트 ▒ 

문제 설명을 읽어보면 처음엔 무슨 소리인가 쉽지만, 굉장히 단순한 문제입니다.

두 개의 정수가 역순으로 연결리스트로 구현되어 있습니다.

ex) 435: 5 -> 3 -> 4
ex) 342: 2 -> 4 -> 3
ex) 456: 6 -> 5 -> 4

이런 규칙의 연결리스트 두 개를 받았을 때, 원래 두 정수의 합을 다시 연결리스트로 반환하는 문제입니다.

 

어차피 각 정수가 역순으로 되어있기 때문에, 리스트를 순서대로 타고 가면 일의 자리부터 접근할 수 있다는 뜻이 됩니다. 따라서, 두 리스트를 단순하게 앞에서부터 접근하면서 더해주는 식으로 새로운 리스트를 만들면, 그게 정답이 됩니다. 중간에 올림 처리만 반복문을 진행하는 과정에서 해주면, 쉽게 풀 수 있습니다.

l1        = 2    -> 4     -> 3
l2        = 6    -> 5     -> 4
answer = 2+6 -> 4+5 -> 3+4
          = 8     -> 9     -> 7

 

<코드(Javascript)>

/**
 * 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) {
    const answer = new ListNode();
    let n1 = l1;
    let n2 = l2;
    let cur = answer;
    let carry = false;
    
    let val = n1.val + n2.val;
    if(val > 9){
        carry = true;
        val = val % 10;
    }
    cur.val = val;
    
    while(n1.next || n2.next){
        n1 = n1.next || new ListNode();
        n2 = n2.next || new ListNode();
        cur.next = new ListNode();
        cur = cur.next;
        val = n1.val + n2.val;
        if(carry){
            val++;
            carry = false;
        }
        if(val > 9){
            carry = true;
            val = val % 10;
        }
        cur.val = val;
    }
    if(carry){
        cur.next = new ListNode(1);
    }
    
    return answer;
};

function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}

 

 

더 많은 코드 보기(GitHub) : github.com/dwkim-97/CodingTest

 

 

반응형