一個找最接近值有關問題,請高手給個思路

來源:互聯網
上載者:User
一個找最接近值問題,請高手給個思路
要做一個東西,其中A的值是已知,需要找到B,B的值為小於A並且是2的平方數。
比如:A=765,要求出B,那麼B就等於512。我想到一個辦法,因為A的值有最大範圍,所以我把2的1次方,2的2次方,2的三次方。。。。,都儲存為數組,然後再用A值和這個數組對比找出符合要求的B值。

但是感覺應該有其他更好的方法,請高手給個思路。謝謝!

------解決方案--------------------
function get2str($n)
{
$len = strlen(decbin($n));
$str2 = '1'. str_repeat('0', $len-1);
return bindec($str2);
}
var_dump(get2str(578));
// int(512)
思路是這樣:
4: 100 3
8: 1000 4
16: 10000 5
32: 100000 6
64: 1000000 7
128: 10000000 8
256: 100000000 9
512: 1000000000 10
1024: 10000000000 11
2048: 100000000000 12
578: 1001000010 10
你可以看到,分別是 十進位數: 二進位字串 長度
578與512的二進位字串同是10位元組長。我不會PHP的位操作,因此我想一定還有更高效簡單的方案。
------解決方案--------------------
請複習一下指數和對數
PHP code
$a = 765;echo pow(2, floor(log($a, 2)));
------解決方案--------------------
1,保留最左邊的1就行了,位元運算。
PHP code
[[email protected] php_project]$ php main.php 765 => 5120 => 0256 => 2561 => 13 => 2255 => 128257 => 256[[email protected] php_project]$ cat main.php > $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;        }}?>
------解決方案--------------------
如果用二進位方式計算,那麼
PHP code
$A = 765;$t = decbin($A);echo bindec(str_pad(1, strlen($t), '0'));
------解決方案--------------------
探討

如果用二進位方式計算,那麼PHP code
$A = 765;
$t = decbin($A);
echo bindec(str_pad(1, strlen($t), '0'));
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.