/*
* @lc app=leetcode.cn id=2 lang=typescript
*
* [2] 两数相加
*
* https://leetcode-cn.com/problems/add-two-numbers/description/
*
* algorithms
* Medium (40.93%)
* Likes: 6980
* Dislikes: 0
* Total Accepted: 1M
* Total Submissions: 2.6M
* Testcase Example: '[2,4,3]\n[5,6,4]'
*
* 给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
*
* 请你将两个数相加,并以相同形式返回一个表示和的链表。
*
* 你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
*
*
*
* 示例 1:
*
*
* 输入:l1 = [2,4,3], l2 = [5,6,4]
* 输出:[7,0,8]
* 解释:342 + 465 = 807.
*
*
* 示例 2:
*
*
* 输入:l1 = [0], l2 = [0]
* 输出:[0]
*
*
* 示例 3:
*
*
* 输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
* 输出:[8,9,9,9,0,0,0,1]
*
*
*
*
* 提示:
*
*
* 每个链表中的节点数在范围 [1, 100] 内
* 0
* 题目数据保证列表表示的数字不含前导零
*
*
*/
// @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
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 {
let pre = 0
let root: ListNode | null = null
let node: ListNode | null = null
while (l1 || l2 || pre) {
const num = pre + (l1?.val ?? 0) + (l2?.val ?? 0)
const cur = new ListNode(num % 10)
pre = Math.floor(num / 10)
if (!node) {
root = node = cur
} else {
node.next = cur
node = cur
}
if (l1) l1 = l1.next
if (l2) l2 = l2.next
}
return root
}
test.each([
{ input: { l1: [2, 4, 3], l2: [5, 6, 4] }, output: [7, 0, 8] },
{ input: { l1: [0], l2: [0] }, output: [0] },
{ input: { l1: [9, 9, 9, 9, 9, 9, 9], l2: [9, 9, 9, 9] }, output: [8, 9, 9, 9, 0, 0, 0, 1] },
])('input: l1 = $input.l1, l2 = $input.l2', ({ input: { l1, l2 }, output }) => {
expect(addTwoNumbers(LinkedList.deserialize(l1), LinkedList.deserialize(l2))).toEqual(LinkedList.deserialize(output))
})