[leetcode, JS] 2. Add Two Numbers

mxxn·2023년 8월 2일
0

leetcode

목록 보기
3/198

문제

문제 링크 : Add Two Numbers

풀이

/**
 * 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 List = new ListNode(0);
  let head = List;
  let sum = 0;
  let carry = 0;

  while(l1!==null || l2!==null || sum>0){
    if(l1 !== null){
      sum += l1.val;
      l1 = l1.next;
    }
    if(l2 !== null){
      sum += l2.val;
      l2 = l2.next;
    }

    if(sum >= 10){
      carry = 1;
      sum = sum - 10;
    }

    head.next = new ListNode(sum);
    head = head.next;

    sum = carry;
    carry = 0;
  }
  return List.next;

};
  1. js에서 linked-list 개념은 처음이라 풀이를 참고하여 진행
  2. while문을 통해 List의 next를 만들어가는 방식
  • Runtime 94 ms, Memory 47 MB
profile
내일도 글쓰기

0개의 댓글