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

1 Answer

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


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

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




/*
run:

3
4

*/

 



answered Dec 14, 2023 by avibootz

Related questions

...