Skip to content

Instantly share code, notes, and snippets.

@segaz2002
Created November 27, 2021 20:15
Show Gist options
  • Save segaz2002/746ca56fe3a39327f0ada8709c6fe4b1 to your computer and use it in GitHub Desktop.
Save segaz2002/746ca56fe3a39327f0ada8709c6fe4b1 to your computer and use it in GitHub Desktop.
Leet Code: 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}
*/
function listLength(lst){
let output = 0;
let current = lst;
while(current != null){
output +=1;
current = current.next;
}
return output;
}
function getIndex(i, lst){
let current = lst;
if(i == 0){
return current.val;
}else{
while(i != 0 && current.next != null){
current = current.next;
i--;
}
return current.val;
}
}
var addTwoNumbers = function(l1, l2) {
const ls1Len = listLength(l1);
const ls2Len = listLength(l2);
const mxLen = Math.max(ls1Len, ls2Len);
let carry = 0;
let res = "";
for(let i = 0; i <= mxLen-1; i++){
let l = 0;
let r = 0;
if(i <= ls1Len-1){
l = getIndex(i, l1);
}
if(i <= ls2Len-1){
r = getIndex(i, l2);
}
let sum = l + carry + r;
if(sum >= 10){
carry = 1;
res += sum - 10;
}else{
res += sum;
carry = 0;
}
}
if(carry != 0){
res += 1;
}
let sumArray = res.split("");
let head = new ListNode();
current = head;
for(let i=0; i <= sumArray.length-1; i++){
current.val = sumArray[i].trim();
if(i != sumArray.length-1){
current.next = new ListNode();
current = current.next;
}
}
return head;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment