Skip to content

Instantly share code, notes, and snippets.

@andresabello
Created June 13, 2020 03:58
Show Gist options
  • Save andresabello/66bf9c3747aedf47fdb639ff3d21dc6a to your computer and use it in GitHub Desktop.
Save andresabello/66bf9c3747aedf47fdb639ff3d21dc6a to your computer and use it in GitHub Desktop.
Add Two Numbers #2 From Leetcode = You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself.
/**
* 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 revL1 = reverse(l1), revL2 = reverse(l2), carry = 0, l3
while(revL1 || revL2) {
let sum = (revL1 !== null ? revL1.val : 0) + (revL2 !== null ? revL2.val : 0) + carry
carry = sum >= 10 ? 1 : 0
let lastDigit = sum % 10
let newNode = new ListNode(lastDigit)
if (l3 == null) {
l3 = newNode
} else {
newNode.next = l3
l3 = newNode
}
if (revL1 != null) revL1 = revL1.next
if (revL2 != null) revL2 = revL2.next
}
if (carry > 0) {
let newNode = new ListNode(carry)
newNode.next = l3
l3 = newNode
}
return l3
};
var reverse = function(head) {
let prev = null
while(head){
let next = head.next
head.next = prev
prev = head
head = next
}
return prev;
}
@andresabello
Copy link
Author

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment