DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 58

The task is to implement a function that counts one in binary form.

The boilerplate code

function countOne(num) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

The binary one is removed repeatedly from the given number until there are no more left

while (num !== 0) {
 num &= num -1
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)