feat: 添加算法题两数相加(leetcode 2)

This commit is contained in:
= 2024-05-15 14:17:38 +08:00
parent 2917871b58
commit 6a5396d54d

View File

@ -0,0 +1,90 @@
/*
给你两个 非空 的链表表示两个非负的整数它们每位数字都是按照 逆序 的方式存储的并且每个节点只能存储 一位 数字
请你将两个数相加并以相同形式返回一个表示和的链表
你可以假设除了数字 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]
解释也就是用列表表示
*/
function addTwoNumbers(l1, l2) {
const head = new ListNode()
let curNode = head
let carry = 0
while (l1!==null || l2!==null) {
let x = l1 !== null ? l1.val : 0
let y = l2 !== null ? l2.val : 0
let 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 = target / 10n
cur.next = target ? new ListNode() : null
cur = cur.next
}
return head
}
// 换一种思路,我们按照顺序压入栈中,再依次弹出,之后生成对应的数,最后再把这个数转化为链表不就行了吗?
// 输入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'
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)));