Writing a function that takes an integer as input, and returns number of bits to binary

Viewed 3636

I'm on a code wars exercise and its not accepting my solution, and throws a type error: Cannot read property 'length' of null. I checked my code on a separate Chrome window and it works perfectly. When the function is called with any integer, I get all the 1's from the binary number. What am I doing wrong?

var countBits = function(n) {
  var result = n.toString(2).match(/1/g).length;
  return result;
};
4 Answers

If you input character in function it can not match, you should add condition to check null.

var result = n.toString(2).match(/1/g) != null ? n.toString(2).match(/1/g).length : 0;

var countBits = function(n) {
  var result = n.toString(2).match(/1/g) != null ? n.toString(2).match(/1/g).length : 0;
  return result;
};
console.log(countBits('a'))

this will return error if string doesn't match your regular expression. do something like this.

var countBits = function(n) {
  var result = n.toString(2).match(/1/g);
  if (result){       
      return result.length;
  }
  return 0;
};

In case there are no 1s (0), match will return null. You could use filter instead:

const countBits = n => [...n.toString(2)].filter(e => e === "1").length;

While there's nothing wrong with turning the number into a string and counting with a regex, you can also do it with simple math — just continuously divide by 2 and look at the number mod 2 until you've reduced it to zero.

var countBits = function(n) {
   let s = 0;
   while (n > 0){
     s += n % 2
     n = Math.floor(n/2)
  }
  return s
};

console.log(countBits(0))
console.log(countBits(2))
console.log(countBits(3))
console.log(countBits(1234))

Related