日期:2014-05-17 浏览次数:20705 次
$a = 765; echo pow(2, floor(log($a, 2)));
------解决方案--------------------
1,保留最左边的1就行了,位运算。
[liangdong@bb-browser-test00.vm.baidu.com php_project]$ php main.php 765 => 512 0 => 0 256 => 256 1 => 1 3 => 2 255 => 128 257 => 256 [liangdong@bb-browser-test00.vm.baidu.com php_project]$ cat main.php <?php function bit_alg($num) { if (!is_int($num)) { return false; } else if ($num === 0) { return $num; } else { $off = 0; while (($num >> $off) != 1) { ++ $off; } return 1 << $off; } } $cases = array(765, 0, 256, 2.3, 1, 3, 255, 257); foreach ($cases as $value) { if (($ret = bit_alg($value)) !== false) { echo $value . " => " . $ret . PHP_EOL; } } ?>
------解决方案--------------------
如果用二进制方式计算,那么
$A = 765; $t = decbin($A); echo bindec(str_pad(1, strlen($t), '0'));
------解决方案--------------------