두 개의 숫자 더하기 - LinkedList

14750 단어 leetcodejavascript
접근법 1: 간단하고 설명적임

/**
 * 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 carry = 0;
    let finalSum = []
    while(l1 || l2){  
        if(l1 && l2){
            let temp = l1.val +l2.val + carry;
            if(temp > 9){
                carry = parseInt(temp / 10);
                let lastNum = temp%10;
                finalSum.push(lastNum);
            }else{
                carry = 0;
                finalSum.push(temp)
            }
            l1 = l1.next;
            l2 = l2.next;
        } 

        if(l1 && !l2){
            let temp = l1.val + carry;
            if(temp > 9){
                carry = parseInt(temp / 10);
                let lastNum = temp%10;
                finalSum.push(lastNum);
            }else{
                 carry = 0;
                finalSum.push(temp)
            }
              l1 = l1.next;
        }
         if(l2 && !l1){
            let temp = l2.val + carry;
            if(temp > 9){
                carry = parseInt(temp / 10);
                let lastNum = temp%10;
                finalSum.push(lastNum);
            }else{
                 carry = 0;
                finalSum.push(temp)
            }
              l2 = l2.next;
        }
    }
    if(carry > 0){
        finalSum.push(carry)
    }
    return addATlast(finalSum);
};

const addATlast = (finalSumArray) => {
    let head = null;
    for(let i=0; i < finalSumArray.length; i++){
       head = createList(finalSumArray[i], head);
    }
    return head;
}
const createList = (val, head) => {
   if (head === null) {
        head = new ListNode(val);
      } else {
        let current = head;
        while (current.next) {
          current = current.next;
        }
        current.next = new ListNode(val);
      }
    return head;
}



접근법 2 : 짧지만 접근법 1과 동일

var addTwoNumbers = function(l1, l2) {
    let head = new ListNode();
    let current = head;
    let carryOver = 0;

    while(l1 || l2){
        let sum = (l1?.val || 0) + (l2?.val || 0) + carryOver;
        if(sum.toString().length>1){
            carryOver = Number(sum.toString().substring(0,1))
            sum = Number(sum.toString().substring(1,2))            
        }else{
            carryOver = 0
        }
        current.next = new ListNode(sum);
        current = current.next ;
        if(l1) l1 = l1.next;
        if(l2) l2 = l2.next;

    }


    if (carryOver>0)  current.next = new ListNode(carryOver);
    return head.next;
};

좋은 웹페이지 즐겨찾기