.Zzumbong

[leetCode/JS] 2. Add Two Numbers 본문

coding test/leetCode

[leetCode/JS] 2. Add Two Numbers

쭘봉 2022. 11. 23. 11:04

문제 설명

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.

입출력 예

Example 1:

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

 

Example 2:

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

 

Example 3:

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.

내 솔루션

  • 아니~~ 이런 것도 나와? 알고리즘 기본이라곤 하지만 실무에서 써본적이 없어서 조금 헤맸다
var addTwoNumbers = function(l1, l2) {
  const List = new ListNode();
  let current = List;
  let carry = 0;
  while(l1 || l2 || carry){
    current.next = new ListNode();
    current = current.next;
    const value = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + carry;
    carry = value > 9 ? 1 : 0;
    current.val = value % 10;
    l1 = l1 ? l1.next : null;
    l2 = l2 ? l2.next : null;
  }
  return List.next
};

감상평

  • 공부 없이 수 많은 코딩테스트를 쳤던 1년전에 나는 대단하구나 어케 통과했냐..
Comments