ZeeshanAli-0704

Posted on

# Add Two Numbers - LinkedList

Approach 1 : Simple & descriptive

``````/**
* 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 carry = 0;
let finalSum = []
while(l1 || l2){
if(l1 && l2){
let temp = l1.val +l2.val + carry;
if(temp > 9){
carry = parseInt(temp / 10);
let lastNum = temp%10;
finalSum.push(lastNum);
}else{
carry = 0;
finalSum.push(temp)
}
l1 = l1.next;
l2 = l2.next;
}

if(l1 && !l2){
let temp = l1.val + carry;
if(temp > 9){
carry = parseInt(temp / 10);
let lastNum = temp%10;
finalSum.push(lastNum);
}else{
carry = 0;
finalSum.push(temp)
}
l1 = l1.next;
}
if(l2 && !l1){
let temp = l2.val + carry;
if(temp > 9){
carry = parseInt(temp / 10);
let lastNum = temp%10;
finalSum.push(lastNum);
}else{
carry = 0;
finalSum.push(temp)
}
l2 = l2.next;
}
}
if(carry > 0){
finalSum.push(carry)
}
return addATlast(finalSum);
};

const addATlast = (finalSumArray) => {
let head = null;
for(let i=0; i < finalSumArray.length; i++){
head = createList(finalSumArray[i], head);
}
return head;
}
const createList = (val, head) => {
if (head === null) {
head = new ListNode(val);
} else {
let current = head;
while (current.next) {
current = current.next;
}
current.next = new ListNode(val);
}
return head;
}

``````

Approach 2 : short but same as Approach 1

``````var addTwoNumbers = function(l1, l2) {
let head = new ListNode();
let current = head;
let carryOver = 0;

while(l1 || l2){
let sum = (l1?.val || 0) + (l2?.val || 0) + carryOver;
if(sum.toString().length>1){
carryOver = Number(sum.toString().substring(0,1))
sum = Number(sum.toString().substring(1,2))
}else{
carryOver = 0
}
current.next = new ListNode(sum);
current = current.next ;
if(l1) l1 = l1.next;
if(l2) l2 = l2.next;

}

if (carryOver>0)  current.next = new ListNode(carryOver);
return head.next;
};

``````