Javascript Number Type Count Bit

Introduction

Write a function that takes an integer as input.

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


var countBits = function(n) {
  return n.toString(2).split("").filter(b => b === "1").length;
};

console.log(countBits(1234));/*from  w w  w.  j a v  a 2  s  . co m*/



PreviousNext

Related