add two number

by mukkaram waheed

JavaScript

class ListNode {
  constructor(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
  }
}

let l1 = new ListNode([9, 9, 9, 9, 9, 9, 9], null);
let l2 = new ListNode([9, 9, 9, 9, 9, 9, 9], null);

//output  [8,9,9,9,0,0,0,1]


var addTwoNumbers = function(l1, l2) {
  const head = new ListNode();
  let cursor = head;
  let carry = 0;
  while (l1 || l2 || carry) {
    cursor.next = new ListNode();
    cursor = cursor.next;

    let val = parseInt((l1 ? l1.val : 0)) + parseInt((l2 ? l2.val : 0)) + parseInt(carry);

    carry = val >= 10 ? 1 : 0;
    cursor.val = val % 10;
    l1 = l1 ? l1.next : null;
    l2 = l2 ? l2.next : null;
  }
  return head.next;
};

/* console.log("addTwoNumbers", addTwoNumbers(l1, l2)) */