2 Add Two Numbers

문제

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.

조건

예제

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

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

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

해결

생각

코드

var addTwoNumbers = function(l1, l2) {
  let totalValue = ""
  let checkNode = l1
  let carry = 0

  while(checkNode) {
    const l1Val = checkNode?.['val'] ? checkNode?.['val'] : 0
    const l2Val = l2?.['val'] ? l2['val'] : 0
    // 둘이 합쳐서 최대는 18
    const total = l1Val + l2Val + (carry > 0? carry : 0)
    const remain = total % 10
    carry = (total / 10) >> 0
    totalValue += remain

    checkNode = checkNode['next']
    if(! checkNode && l2){
      checkNode = l2['next']
      l2 = null
      continue;
    }
    l2 = l2?.['next'] ? l2['next'] : null
  }
  if(carry > 0) {
    totalValue += carry
  }

  let totalValueIdx = totalValue.length -1
  let answer = null; // null로 안해두면 undefined가 들어가서 잘못된 답이라는 에러 발생
  while (totalValueIdx >= 0){
    answer = {
      val: ~~totalValue[totalValueIdx--],
      next: answer
    }
  }

  return answer
};