leetcode 2 - Add Two Numbers

목차

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

주어진 정수 배열을 이용하여 두 숫자의 인덱스를 반환하여 특정 대상에 합산합니다.
각 입력에는 정확히 하나의 솔루션이 있다고 가정 할 수 있으며 동일한 요소를 두 번 사용할 수 없습니다.

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    let node = new ListNode(0);
    let root = node;
    var carry = 0, value = 0;
    while(l1 !== null || l2 !== null || carry > 0){
        let val1 = (l1 === null) ? 0 : l1.val;
        let val2 = (l2 === null) ? 0 : l2.val;
        
        value = val1 + val2 + carry;
        carry = Math.floor(value / 10);
        
        node.next = new ListNode(value % 10);
        
        if(l1 != null){
            l1 = l1.next;   
        }
        if(l2 != null){
            l2 = l2.next;
        }
        
        node = node.next;
        
    }
    return root.next;
};
 

 

  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유