본문 바로가기

[LeetCode] Add Two Number

안자매 2022. 6. 29.
반응형

 

개인적으로 공부하면서 기록하는 공간으로
잘못된 정보는 댓글을 통해 알려주시면 감사하겠습니다 :-)

▪ ▪ ▪ ▪ ▪

 

 

🎈문제

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.

 

Example1: 

Input: l1 = [2, 4, 3], l2 = [5, 6, 4]
Output: [7, 0, 8]
Explanation: 342 + 465 = 807

 

Example2:

Input: l1 = [0], l2 = [0]
Output: [0]

 

Example3:

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.

 

💡 문제해석

주어진 Linked List을 역순으로 읽은 숫자의 합을 역순으로 반환하는 문제이다.

 


 

🎈문제 풀이

/**
 * 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 rootNode = new ListNode();
    let over =  0;
    currentNode = rootNode;
    
    while(l1 !== null || l2 !== null) {
        currentNode.next = new ListNode();
        currentNode = currentNode.next;
        
        let val1 = l1 !== null ? l1.val : 0;
        let val2 = l2 !== null ? l2.val : 0;
        
        currentNode.val = val1 + val2 + over;
        if(currentNode.val >= 10) {
            currentNode.val = currentNode.val % 10;
            over = 1;
        }
        else over = 0;
        
        if(l1 !== null) l1 = l1.next;
        if(l2 !== null) l2 = l2.next;
    }
    
    if(over === 1) {
        currentNode.next = new ListNode(1);
    }
    
    return rootNode.next;
}

문제 설명만 읽었을 때 배열로 착각하고 reverse와 같은 메소드를 사용해보려고 했지만

문제 풀이 상단에 보면 Linked List형태로 주어져 배열에서 사용하는 메소드를 사용할 수 없다는 것을 알 수 있을 것이다.

 

💛 Varialbes

over - 각 노드는 단일 숫자(0~9)이기 때문에 각 자리수의 합이 10 이상이 될 때 다음 노드로 올림 처리 해줄 때 사용한다. 

rootNode - ListNode가 단방향이므로 return하는 용도로 사용한다.

currentNode - rootNode에 l1, l2의 값을 더할 목적으로 사용한다.

 

 

sum에 대한 output을 저장할 ListNode 객체를 생성한다.

 

 

각 노드는 단일 숫자이므로 두 수의 합이 10 이상이 될 경우 over변수에 1을 담아 올림처리를 해주고 나머지 값을currentNode의 value에 저장한다.

 

currentNode의 value에 val1 + va2 + over 데이터를 넣어주고 난 뒤 l1의 포인터를 다음으로 이동하여 l1과 l2 노드가 없을 때 까지 반복한다.

 

 

 

 

🎈문제 풀어보기

 

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

 

 

Reference

https://mori29.tistory.com/13

 

 

댓글