The task is to implement a function that counts one in binary form.
The boilerplate code
function countOne(num) {
// your code here
}
The binary one is removed repeatedly from the given number until there are no more left
while (num !== 0) {
num &= num -1
}
Every time a binary one is removed, the counter increases count++
When the number reaches 0, the counter shows how many 1s were removed, which is exactly how many 1s were in the binary representation.
The final code
function countOne(num) {
// your code here
let count = 0;
while(num !== 0) {
num &= num - 1;
count++
}
return count;
}
That's all folks!
Top comments (0)