我确信我的代码是正确的,但它返回1364而不是正确答案1366。 我测试了我的代码2 ^ 15并且它返回了正确答案26.我还尝试了一些其他数字,所有这些都给了我一个正确的答案。 我知道我的代码是非常基本的,我不太了解Javascript,我对替代解决方案持开放态度,但我正在寻找解释为什么我的代码不起作用。
//adds digits of this number
sum(Math.pow(2,1000));
function sum(x) {
//the upper limit of the number
var c = Math.floor(Math.log10(x));
//the sum
var s = 0;
//the ith digit
var a;
for (var i = c; i >= 0; i--) {
//this works, test by removing the slashes before console.log(a)
a = Math.floor((x % Math.pow(10,i+1)) / Math.pow(10,i));
s += a;
//console.log(a);
}
console.log(s);
}
答案 0 :(得分:0)
扩展guest271314的评论:
Javascript号码有IEEE 754 double-precision floating point行为。这意味着Javascript无法准确表示2 53 之上的整数。
> Number.isSafeInteger(Math.pow(2, 15))
< true
> Number.isSafeInteger(Math.pow(2, 1000))
< false
要在Javascript中解决此问题,您需要使用2 1000 的不同表示形式。因为您关心的唯一操作是求幂和读出数字基数10,所以一个可能的表示形式是十进制字符串,自己实现乘法。