I need explanation for “Bit Counting” challenge on
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
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
Link to the challenge:
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'
Count the number of ones in the resultant string:
[...'10011010010'].filter(el => el === '1').length
const binary = (int).toString(2);
return [...binary].filter(el => el === '1').length;
See below for further reading.
number of bits
Does number of bits means
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.