Reputation: 7468
From other searches, I found that this problem is called 'Hamming Weight' or 'Population Count'. There are lot of answers out there given with so many statistics? I need to find the solution in a simple way? Complexity is not a big deal. Is there any in-built function in JavaScript like Java's Integer.bitCount?
I'm currently doing this as follows.
var binary = 3;
var original = binary;
var count = 0;
while(binary>0)
{
binary = binary >> 1 << 1;
if(original-binary==1)
count++;
original = binary >> 1;
binary = original;
}
Is there a better, more simple as well as elegant way for this?
Upvotes: 5
Views: 9106
Reputation: 286
function numOfOnes(n) {
if(n === 0) return n;
return (n & 1) + numOfOnes(n >>= 1);
}
Basically this approach belongs to recursive call.
It has the base condition when no number to evaluate.
Otherwise it calls itself on (n >>= 1)
and add last digit (n & 1)
to result.
eg. 7 has binary representation 111 = 1+1+1 = 3
17 has binary representation 10001 = 1+0+0+0+1 = 2
Upvotes: 1
Reputation: 25
function countOnesInDecimal(num) {
let count = 0;
let binary = num.toString(2);
const splitted = binary.split('');
for (const iterator of splitted) {
if (iterator === `1`) {
count += 1;
}
}
return count;
}
console.log(countOnesInDecimal(3));
Upvotes: 0
Reputation: 19329
A simple way without using built-in functions:
function f(n){
let i = 0;
do if(n&1) ++i; while(n>>=1)
return i;
}
// example:
console.log(f(7)); // 3
Upvotes: 3
Reputation: 39
If you want to count 1 digit in binary representation we can use regular expression like this.
number.toString(2).match(/1/g).length
Upvotes: 3
Reputation: 5201
try this
var binary = 10;
var result = binary.toString(2); //Converts to binary
var count = result.split(1);// count -1 is your answer
alert((result.split('1').length-1));
can also be written as
(binary.toString(2).split('1').length-1)
toString(2) : helps to split it in a base2 format which is binary, can do this in a range of 2- 36 (iam not sure about the range)
Upvotes: 6