Add Two Numbers
Description
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 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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
Solution(javascript)
function ListNode(val) {
this.val = val
this.next = null
}
const addTwoNumbers = (l1, l2) => {
let h1 = l1
let h2 = l2
let digit = 0
let head = null
let current = null
while (h1 || h2) {
const num1 = h1 ? h1.val : 0
const num2 = h2 ? h2.val : 0
let value = num1 + num2 + digit
if (value >= 10) {
value -= 10
digit = 1
} else {
digit = 0
}
h1 = h1 ? h1.next : null
h2 = h2 ? h2.next : null
const node = new ListNode(value)
if (!head) {
head = node
current = node
} else {
current.next = node
current = node
}
}
if (digit === 1) {
current.next = new ListNode(1)
}
return head
}