Leetcode - Add Two Numbers - Two Solutions
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.
Full problem here.
Solution 1. Based on this solution
var addTwoNumbers = function(l1, l2) {
const head = new ListNode(0)
let firstNode = l1
let secondNode = l2
let currentNode = head
let carry = 0
while (firstNode || secondNode || carry) {
const firstValue = firstNode?.val || 0
const secondValue = secondNode?.val || 0
const sumOfValues = firstValue + secondValue + carry
const remainder = sumOfValues % 10
carry = (sumOfValues - remainder) / 10
currentNode.next = new ListNode(remainder)
currentNode = currentNode.next
firstNode = firstNode?.next
secondNode = secondNode?.next
}
return head.next
};
Solution 2. Based on this solution
var addTwoNumbers = function(l1, l2) {
const getNextNode = (firstNode, secondNode, carry) => {
const firstValue = firstNode?.val || 0
const secondValue = secondNode?.val || 0
const sumOfValues = firstValue + secondValue + carry
const remainder = sumOfValues % 10
const newCarry = (sumOfValues - remainder) / 10
if(firstNode?.next || secondNode?.next || newCarry) {
const nextNode = getNextNode(firstNode?.next, secondNode?.next, newCarry)
return new ListNode(remainder, nextNode)
}
return new ListNode(remainder)
}
return getNextNode(l1, l2, 0)
}