(js)二进制中1的个数
let n = 928;
// 挪动1的位置
console.log(n.toString(2));
let count = 0;
for (let i = 0; i < 32; i++) {
if ((n & (1 << i)) === (1 << i)) {
count++;
}
}
console.log(count);
// 挪动本身
count = 0;
for (let i = 0; i < 32; i++) {
if ((n >>> i) & 1) {
count++;
}
}
console.log(count);
// 使用(x-1)&x
count = 0;
while (n !== 0) {
n = ((n - 1) & n);
count++;
}
console.log(count);
1110100000
4
4
4