Reputation: 179
I am attempting to write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case.
Here is my answer:
var newArr;
var count = 0;
function countBits(num){
newArr = num.toString(2).split('').map(function(el){
if(el == '1')
count++
});;
return count;
}
In my program when I call countBits(7) it returns //3 but when I submit my response it says it is returning //4. Can someone see what I am missing in my response based on question?
Upvotes: 0
Views: 3729
Reputation: 11
function countBits(num){
// convert num Base10 to Base2
let base2 = num.toString(2)
// declare variable for sum of bits
let sum = 0
// for loop to check bits (bit = 1) and ignore Zeros in the String base2
for(let i = 0; i < base2.length; i++){
if(base2[i] == 1){
// use Number() to convert string to number
count += Number(base2[i])
}
}
return sum ;
}
Upvotes: 0
Reputation: 11
function countBits(num){
/* Convert num Base10 to num Base2
then find Ones and save them in an array
length of the array is equal their sum */
return num.toString(2).match(/1/g).length
}
Upvotes: 0
Reputation: 664548
Your problem is that you are declaring the variables outside of the function, so when the function is called multiple times they'll keep their values and just increase the count.
Btw, you also shouldn't use map
if you don't want to create another array - so better do
function countBits(num){
var newArr = num.toString(2).split('').map(Number);
var count = 0;
for (var i=0; i<newArr.length; i++)
count += newArr[i];
}
return count;
}
or
function countBits(num){
return num.toString(2).split('').reduce(function(count, el) {
return count + (el == "1");
}, 0);
}
Upvotes: 3