# Need explanation for "Bit Counting" challenge

I need explanation for “Bit Counting” challenge on codewars platform.
The instruction says:

Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.

Example : The binary representation of `1234` is `10011010010` , so the function should return `5` in this case

So I did not understand how do we return `5` and what should I do to return `5` and why the answer is `5`?

Hi,

1. Convert the integer to binary. You can use `Number.toString(2)` as we aren’t dealing with a negative. E.g. `(1234).toString(2) => '10011010010'`
2. Count the number of ones in the resultant string: `[...'10011010010'].filter(el => el === '1').length`

Together:

``````function getNoBits(int){
const binary = (int).toString(2);
return [...binary].filter(el => el === '1').length;
}

console.log(getNoBits(1234));
// 5
``````

1 Like

Does number of bits means `1` ?

Number of bits means the minimum number of bits required to represent the number, excluding of course leading zeros.

You can easily convert to binary using toString, and count the length of the resulting value to get the number of bits.

``````const amount = 83;
const numberOfBits = Number(amount).toString(2).length;
``````

However, the question is not about finding the total number of bits. It asks for “the number of bits that are equal to one in the binary representation”, for which the code from Jame’s qpost neatly solves.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.