Coding while sleep deprived

Today I went to the CodeWars website. I was greeted with a little challenge.

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.

Keep in mind that I didn't sleep last night, and as I write this it's 7:15am. I'm cranky, tired, sleep deprived, and I can't sleep.

Well, what could a developer like me do in such a situation. The "chalenge" was super easy.

Less than a minute I banged up the following function:


var countBits = function(n) {
  if (n < 0)
    throw new Exception();
  
  var cnt = 0;
  while (n > 0) {
    cnt += (n & 1) == 1 ? 1 : 0;    
    n = Math.floor(n / 2);
  }

  return cnt;
};

Passed the tests with flying colors.

Why did I use Math.floor instead of a simple bit shift (>>)?

Simple. Because at the CodeWars website, this little code would run on JavaScript and the bit shift operation returns a 32-bit value, and I wanted to be sure that the function could operate with 64-bit values.

Comments