6__Bit_Counting.js 486 B

12345678910111213
  1. // Write a function that takes an integer as input,
  2. // and returns the number of bits that are equal to one in the binary representation of that number.
  3. // You can guarantee that input is non - negative.
  4. // Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
  5. function bitCounting(n) {
  6. let count = 0;
  7. (+n.toString(2))
  8. .toString()
  9. .split("")
  10. .forEach((x) => (+x ? ++count : count));
  11. return count;
  12. }