/*
* @lc app=leetcode.cn id=445 lang=typescript
*
* [445] 两数相加 II
*/
// @lc code=start
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {}
// @lc code=end
function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
const arr1: ListNode[] = [],
arr2: ListNode[] = []
while (l1) {
arr1.push(l1)
l1 = l1.next
}
while (l2) {
arr2.push(l2)
l2 = l2.next
}
const arr3: ListNode[] = []
let pre = 0
while (arr1.length || arr2.length || pre) {
const num = (arr1.pop()?.val ?? 0) + (arr2.pop()?.val ?? 0) + pre
const cur = new ListNode(num % 10)
arr3.push(cur)
pre = Math.floor(num / 10)
}
arr3.reverse()
let root: ListNode | null = null,
node = root
for (let i = 0; i < arr3.length; i++) {
if (!node) node = root = arr3[i]
else {
node.next = arr3[i]
node = arr3[i]
}
}
return root
}
test.each([
{ input: { l1: [7, 2, 4, 3], l2: [5, 6, 4] }, output: [7, 8, 0, 7] },
{ input: { l1: [2, 4, 3], l2: [5, 6, 4] }, output: [8, 0, 7] },
{ input: { l1: [0], l2: [0] }, output: [0] },
])('input: l1 = $input.l1, l2 = $input.l2', ({ input: { l1, l2 }, output }) => {
expect(addTwoNumbers(LinkedList.deserialize(l1), LinkedList.deserialize(l2))).toEqual(LinkedList.deserialize(output))
})