Open geekelo opened 2 months ago
To solve this problem, you need to traverse both linked lists simultaneously, adding the corresponding digits along with any carry from the previous addition. Here's a JavaScript function to achieve this:
var addTwoNumbers = function(l1, l2) {
let dummyHead = new ListNode(0);
let current = dummyHead;
let carry = 0;
while (l1 !== null || l2 !== null) {
const x = l1 !== null ? l1.val : 0;
const y = l2 !== null ? l2.val : 0;
const sum = x + y + carry;
carry = Math.floor(sum / 10);
current.next = new ListNode(sum % 10);
current = current.next;
if (l1 !== null) l1 = l1.next;
if (l2 !== null) l2 = l2.next;
}
if (carry > 0) {
current.next = new ListNode(carry);
}
return dummyHead.next;
};
This function takes two linked list nodes, l1
and l2
, as input and returns the sum as a new linked list.
Make sure you define the ListNode
class before using this function. The ListNode
class typically looks like this:
function ListNode(val) {
this.val = val;
this.next = null;
}
This code will handle cases where the lengths of the input linked lists are not the same and where there is a carry at the end of the addition.
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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
var addTwoNumbers = function(l1, l2) { // if l1.next_node exists };