How to write a function to determine the population count of a 16-bit integer using php or javascript. Population count is defined as the number of bits that are "turned on," or in others, it is the number of 1s in a binary representation of a number. For example, the binary number 0b0000 has a population count of 0 because there aren't any 1 bits. 0b0101 has a population count of 2, because 2 bits turned on; 0b1110 has a population count of 3. 0b1111111111111111 has a population count if 16 because there are sixteen 1 bits. Your function should accept an INTEGER argument and return an INTEGER containing its population count. Example:
f(0) = 0
f(1) = 1
f(2) = 1
f(3) = 2
f(4) = 1
f(5) = 2
How to write a function to determine the population count of a 16-bit integer using php or javascript. Population count is defined as the number of bits that are "turned on," or in others, it is the number of 1s in a binary representation of a number. For example, the binary number 0b0000 has a population count of 0 because there aren't any 1 bits. 0b0101 has a population count of 2, because 2 bits turned on; 0b1110 has a population count of 3. 0b1111111111111111 has a population count if 16 because there are sixteen 1 bits. Your function should accept an INTEGER argument and return an INTEGER containing its population count. Example:
f(0) = 0
f(1) = 1
f(2) = 1
f(3) = 2
f(4) = 1
f(5) = 2
Share Improve this question edited Oct 13, 2010 at 2:13 Kirk Strauser 31k5 gold badges52 silver badges69 bronze badges asked Oct 13, 2010 at 1:47 devzonedevzone 3051 gold badge12 silver badges25 bronze badges 2-
@EboMike -
Your function should accept an INTEGER argument and return an INTEGER containing its population count.
Not so much sounds like as almost definitely is homework. Pretty sad that devzone wouldn't even at least try this before asking the question. What has intellectualism e to these days? Get off my lawn before I turn on the sprinklers. – treeface Commented Oct 13, 2010 at 2:00 - @treeface: Yeah, I wish people wouldn't contribute answers to those kind of questions until the person at least shows some effort on their part. Those young whippersnappers! – EboMike Commented Oct 13, 2010 at 2:36
3 Answers
Reset to default 6Using bitwise and and right shift
function count(n){
c =0;
while(n){
c += n&1;
n = n>>1;
}
return c;
}
The badass way?
var x=0xfffe;
x -= ((x >> 1) & 0x55555555);
x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
x = (((x >> 4) + x) & 0x0f0f0f0f);
x += (x >> 8);
x += (x >> 16);
alert(x & 0x0000003f); //15
Not necessarily badass, but it works...
<?php
$number = 3;
echo "Number: " . $number . "\n";
$bin_number = decbin($number);
$population_count = 0;
echo "Binary String Conversion: " . $bin_number . "\n";
for ($i = strlen($bin_number) - 1; $i >= 0; --$i) {
$population_count += $bin_number[$i];
}
echo "Population Count: " . $population_count . "\n";
?>