开发者

How to write a function to determine the population count of a 16-bit integer using php or javascript?

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


Using 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";
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜