gpt4 book ai didi

javascript - 为什么这个函数返回 "'\'1\' ' "according to codewars?

转载 作者:行者123 更新时间:2023-11-29 15:58:34 26 4
gpt4 key购买 nike

因此,我正在尝试解决这个代码战问题 (https://www.codewars.com/kata/5518a860a73e708c0a000027/train/javascript),但我的函数并没有返回像“1”这样的常规字符串,而是返回类似“'\'1\''”的内容,根据密码战。为什么是这样?我的代码如下:

function lastDigit(as){ 
var product = "1";
for(var i = as.length - 1; i >= 0; i--){
var num = as[i]
//console.log(num)
//console.log(bigPower(num.toString(), product))
product = bigPower(as[i].toString(), product);
}
var prodArr = product.split("");
console.log(prodArr[prodArr.length - 1].toString());
return prodArr[prodArr.length - 1].toString();
}


function bigPower(base, exponent){
var product = base;
for(var i = 1; i < parseInt(exponent); i++){
product = multiply(product.toString(), base.toString());
}
return product;
}



function multiply(a, b) {
const product = Array(a.length+b.length).fill(0);
for (let i = a.length; i--; null) {
let carry = 0;
for (let j = b.length; j--; null) {
product[1+i+j] += carry + a[i]*b[j];
carry = Math.floor(product[1+i+j] / 10);
product[1+i+j] = product[1+i+j] % 10;
}
product[i] += carry;
}
return product.join("").replace(/^0*(\d)/, "$1");
}

最佳答案

return 语句中使用parseInt 函数解析字符串并作为整数返回。

  return parseInt(prodArr[prodArr.length - 1].toString());

function lastDigit(as){ 
var product = "1";
for(var i = as.length - 1; i >= 0; i--){
var num = as[i]
product = bigPower(as[i].toString(), product);
}
var prodArr = product.split("");
return parseInt(prodArr[prodArr.length - 1].toString());
}


function bigPower(base, exponent){
var product = base;
for(var i = 1; i < parseInt(exponent); i++){
product = multiply(product.toString(), base.toString());
}
return product;
}

function multiply(a, b) {
const product = Array(a.length+b.length).fill(0);
for (let i = a.length; i--; null) {
let carry = 0;
for (let j = b.length; j--; null) {
product[1+i+j] += carry + a[i]*b[j];
carry = Math.floor(product[1+i+j] / 10);
product[1+i+j] = product[1+i+j] % 10;
}
product[i] += carry;
}
return product.join("").replace(/^0*(\d)/, "$1");
}
console.log(lastDigit([3, 4, 2]))

关于javascript - 为什么这个函数返回 "'\'1\' ' "according to codewars?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55796910/

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