본문 바로가기
LeetCode/코딩 테스트 스터디 1주차

[LeetCode] 2. Add Two Numbers 풀이

by inwoo1324 2022. 7. 10.

0. 문제

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

 개의 음이 아닌 정수를 나타내는 두 개의 비어 있지 않은 연결 목록이 제공됩니다.

숫자는 역순 으로 저장 되며 각 노드에는 단일 숫자가 포함됩니다. 두 숫자를 더하고 합을 연결 목록으로 반환합니다.

#1
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
#2
Input: l1 = [0], l2 = [0]
Output: [0]
#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.언어

자바스크립트(JavaScript)

 

 

2. 문제 풀이

var addTwoNumbers = function(l1, l2) {
    const res=new ListNode(); //리스트 생성
    let res_L=res,
        value=0; 
    
    while (l1 !== null || l2 !== null){
        let v1 = 0, v2 = 0;
        if (l1 !== null){     // l1 = null -> v1 = 0
            v1 = l1.val;
            l1=l1.next;
        }
        if (l2 !== null){     // l2 = null -> v2 = 0
            v2 = l2.val;
            l2=l2.next;
        }
        
        res_L.val = (v1+ v2 + value) % 10;     // 현재 노드에 값 넣기
        value = (v1 + v2 + value) >= 10 ? 1 : 0;
        
        if (l1 !== null || l2 !== null){       // l1,l2 다음 노드가 없을 시 노드 생성하지 않음 
            res_L.next = new ListNode();       // 다음 노드 생성
            res_L = res_L.next;
        }
    }
    if (value) res_L.next = new ListNode(1);
    return res;

};


function ListNode(val, next) {
    this.val = (val===undefined ? 0 : val)
    this.next = (next===undefined ? null : next)
}
Runtime: 152 ms, faster than 56.04% of JavaScript online submissions for Add Two Numbers.
Memory Usage: 47.4 MB, less than 54.95% of JavaScript online submissions for Add Two Numbers.

연결리스트가 어색해서 푸는 데 오래 걸렸던 문제

조건식이 조금 많이 들어간 거 같아 나중에 다시 풀어볼만한 문제다.