如何从javascript中的大量数字中计数? [英] How could I count bit from large number in javascript?
问题描述
我有很多存储在字符串中.
I have a large number stored in string.
let txt = '10000000000000041';
所以我怎么计数以二进制格式显示的位.例如,9的二进制格式是1001,而1的二进制数都不是2.
So how could I count bit presenting in it's a binary format. for example, the binary format of 9 is 1001, and no of 1's is 2.
我到目前为止所做的:
const countOne = (num) => {
let c = 0;
while (num > 0) {
num &= num - 1;
c++;
}
return c;
}
console.log(countOne(+'9'));
console.log(countOne(+'10000000000000041'));
此代码可以正常工作,但不能实现较大的值,因为JavaScript中的Number
无法容纳如此大的值,因此给出了错误的答案.
This code is working fine, but not for large value, because Number
in JavaScript cannot hold such large value, so it's giving the wrong answer.
我发现了类似的问题,但不是很有价值.
I found similar questions but not for large value.
推荐答案
在较新的引擎(至少是Chrome,FF,Opera和Node)中,请参见
In newer engines (Chrome, FF, Opera, and Node at least, see compatibility table), just cast to a BigInt
first:
let txt='10000000000000041';
const countOne = (num) => {
let c = 0;
while (num > 0) {
num &= num - 1n;
c++;
}
return c;
}
console.log(countOne(BigInt(txt)));
console.log(countOne(BigInt(1)));
console.log(countOne(BigInt(2)));
console.log(countOne(BigInt(3)));
console.log(countOne(BigInt(4)));
console.log(countOne(BigInt(5)));
console.log(countOne(BigInt(6)));
console.log(countOne(BigInt(7)));
<script>
try {
eval('1n');
} catch(e) {
throw "Your browser doesn't support BigInt syntax yet";
}
</script>
10000000000000041
以二进制是 100011100001101111001001101111110000010000000000101001
,因此23是正确的:
10000000000000041
in binary is 100011100001101111001001101111110000010000000000101001
, so 23 is correct:
console.log(
[...'100011100001101111001001101111110000010000000000101001']
.reduce((a, b) => a + (b === '1'), 0)
);
这篇关于如何从javascript中的大量数字中计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!