gpt4 book ai didi

javascript - 变量似乎没有获得新值

转载 作者:太空宇宙 更新时间:2023-11-04 15:59:05 26 4
gpt4 key购买 nike

  function reachOne(integer) {
//deal with errors in input
var array = [];
//initialize multiply by putting it equal to 1
var multiply = 1;
var count = 0;

if (integer < 0) {
document.write('Do it again, Input should be a positive Integer')
} else if (integer < 10 && integer >= 0) {
document.write(count);
} else {

do {
for (var i = 0; i < integer.length; i++) {
multiply = multiply * integer.charAt(i);
//if i try to write document.write(multiply), nothing appears
console.log("HELLO");
}
count++
}

while (multiply >= 10)



}
//if I write document.write(multiply) here, the result is 1 and not the product of all the numbers
}
reachSingle(254)

----------

上面的代码应该采用一个正整数,并返回该整数内的数字必须相乘才能得到一位数字的次数。示例:254 将给出 2:2*5*4=40 和 4*0 = 0。

最佳答案

这应该可以做到:

function reachOne(integer, count) {

if (isNaN(integer) || integer < 1) return 0;

var multiply = 1;
if (isNaN(count)) count = 1;

while (integer > 0) {
multiply = multiply * (integer % 10);
integer = Math.floor(integer / 10);
}
if (multiply > 9) return reachOne(multiply, ++count);
return count;
}

console.log(reachOne(254));

关于javascript - 变量似乎没有获得新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42423637/

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