var num = 10234657899876543299999991;
var strNum = num.toString();
var total = 1;
var greatest = 1;
for(var start = 0; start <= strNum.length; start ++){
for(var i = start; i <= start + 3; i ++){
total *= strNum.charAt(i);
}
if(total > greatest){
greatest = total;
}
total = 1;
}
alert(greatest);
我的代码设计为循环var num,并返回4个连续数字的最高倍数。在这个例子中,答案明显是在向编号末尾的九个块中的4 x 9。然而,正在发生的是,一旦多次开始变得越来越少(即在第一个2个9和2个8之后),结果将不再存储,并且8 x 9 x 9 x 8的结果是回。如何通过var num?
告诉我的代码继续寻找大的倍数答案 0 :(得分:1)
不是将num
转换为字符串,而是将其存储为字符串:
var strNum = "10234657899876543299999991";
这将为您提供预期的结果,即9 ^ 4(或6561):
var strNum = "10234657899876543299999991";
var total = 1;
var greatest = 1;
for(var start = 0; start <= strNum.length; start ++){
for(var i = start; i <= start + 3; i ++){
total *= strNum.charAt(i);
}
if(total > greatest){
greatest = total;
}
total = 1;
}
alert(greatest);
&#13;
问题是,在您的代码中,strNum
并不是一个字符串,其所有数字都是num
。相反,它是一串科学记谱法。检查一下:
var num = 10234657899876543299999991;
var strNum = num.toString();
console.log(strNum);
&#13;
而那(1.0234657899876543e + 25)远远超过MAX_SAFE_INTEGER:
console.log(Number.MAX_SAFE_INTEGER.toExponential())
&#13;