How to count the total bits of a number that equal to one (1) in Node.js

1 Answer

0 votes
function getTotalOneBits(num) {
    const binary = num.toString(2);
    
    return [...binary].filter(el => el === '1').length;
}


let num = 42;
console.log(getTotalOneBits(num)); // 00101010

num = 45;
console.log(getTotalOneBits(num)); // 00101101




/*
run:

3
4

*/

 



answered Dec 14, 2023 by avibootz
edited Dec 14, 2023 by avibootz
...