algorighm/leetcode/中等/两数相加.js
2024-05-19 03:36:36 +08:00

91 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* leetcode 2
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
输入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]
解释:也就是用列表表示
*/
// 换一种思路,我们按照顺序压入栈中,再依次弹出,之后生成对应的数,最后再把这个数转化为链表不就行了吗?
// 输入l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
// 输出:[8,9,9,9,0,0,0,1]
import { LinkList, LinkListNode as ListNode } from '../../list/index.js';
function addTwoNumbers(l1, l2) {
const head = new ListNode();
let curNode = head;
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;
curNode.val = sum % 10;
carry = Math.floor(sum / 10);
if (l1 !== null) l1 = l1.next;
if (l2 !== null) l2 = l2.next;
if (carry > 0 || l1 != null || l2 != null) {
curNode.next = new ListNode();
curNode = curNode.next;
}
}
if (carry !== 0) {
curNode.val = carry;
}
return head;
}
function addTwoNumbers2(l1, l2) {
const task1 = [];
const task2 = [];
while (l1 || l2) {
if (l1) {
task1.push(l1.val);
l1 = l1.next;
}
if (l2) {
task2.push(l2.val);
l2 = l2.next;
}
}
let target = BigInt(task1.reverse().join('')) + BigInt(task2.reverse().join(''));
// console.log(Number(task1.reverse().join('')));
console.log(target);
const head = new ListNode();
let cur = head;
while (target) {
cur.val = target % 10n;
target /= 10n;
cur.next = target ? new ListNode() : null;
cur = cur.next;
}
return head;
}
const l1 = LinkList.fromArray(
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
).head;
const l2 = LinkList.fromArray([5, 6, 4]).head;
// console.log(LinkList.prototype.toString.apply(addTwoNumbers(l1,l2)));
console.log(LinkList.prototype.toString.apply(addTwoNumbers2(l1, l2)));
console.log(LinkList.prototype.toString.apply(addTwoNumbers(l1, l2)));