gpt4 book ai didi

javascript - Leetcode 两个数字相加 Q : how to create a linkedlist from a number?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:55 27 4
gpt4 key购买 nike

在这个问题中:https://leetcode.com/problems/add-two-numbers/description/ ,我已经想出了如何获取数字总和(即 807),但现在我需要将该数字转换为链表(例如 7 -> 0 -> 8)。

如何从数字创建链表?

创建列表节点的类函数:

function ListNode(val) {
this.val = val;
this.next = null;
}

我的其余代码:

var addTwoNumbers = function(l1, l2) {

function findVal(linkedList) {
return linkedList.next == null ? linkedList.val.toString() : linkedList.val.toString() + findVal(linkedList.next);

}

var l1num = parseInt(findVal(l1).split('').reverse().join(''));
var l2num = parseInt(findVal(l2).split('').reverse().join(''));
var sum = l1num + l2num;

// Create linked list from sum

最佳答案

如果将数字转换为数组,则可以使用 array.prototype.reduce 函数。

let number = 807;

function ListNode(val) {
this.val = val;
this.next = null;
}


// Convert the number into a string and split that into an array of digits
let arr = Array.from(number.toString());

// Iterate through the elements, and create the nodes
let head = arr.reduce((nextNode, curr) => {
let node = new ListNode(curr);
node.next = nextNode;
return node;
}, null);


// Print out the values
let node = head;
while(node) {
console.log(node.val);
node = node.next
}

关于javascript - Leetcode 两个数字相加 Q : how to create a linkedlist from a number?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47681270/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com