2017-03-09 58 views
-2
$a = 1; 
$b = 2; 
$c = 4; 
$d = 8; 
$e = 16; 
$f = 32; 
$g = 64; 
    . 
    . 
    . 

上面的序列是n的2次冪,$ n是上面幾個序列的數目,如果給你$ n,用一個算法找到$ n是由幾個一起去它一個關於PHP十進制到二進制的算法

+0

問題需要添加更多的細節,比如你想要達到什麼目的?什麼是預期的結果等... –

+0

你想要這樣的: - https://eval.in/751140 –

+0

我把我的問題做了一些修改 – Zhmchen

回答

0

你可以得到單個位(爲你變量$ a,$ b,...)與bitwise operators

例如: 檢查該位被設置

<?php 
$n = 21; //number received from somewhere 

if ($n & 1 == 1) { 
    echo "least significant bit is set"; 
} 

if ($n & 2 == 2) { 
    echo "second least significant bit is set"; 
} 

if ($n & 5 == 5) { 
    echo "third least and least significant bits are set"; 
} 

if ($n & 3 == 1) { 
    echo "least significant bit is set and second least significant bit is unset"; 
} 
?> 

例2:按位加法和乘法

<?php 
$n1 = 1 | 8 | 16; // 1 + 8 + 16 = 25 
$n2 = 2 | 8; // 2 + 8 = 10 

echo "$n1 and $n2\n"; // output: "25 and 10" 
echo ($n1 | $n2) . "\n"; // bitwise addition 25 + 10, output: "27" 
echo ($n1 & $n2) . "\n"; // bitwise multiplication 25 * 10, output: "8" 
?> 

示例3:這就是你需要

POW(2,$ I)在這種情況下產生編號爲1,2,4,8,16,...,這些編號的二進制表示是:0000001,00000010,00000100,00001000,...,

按位與操作者進行零位,其中至少一個操作數具有零位,所以你可以很容易地位得到整數位

這是如何按位和作品:1101 & 0100 = 0100,1101 & 0010 = 0000

<?php 
// get number from somewhere 
$x = 27; // binary representation 00011011 

// let's define maximum exponent of 2^$a (number of bits) 
$a = 8; // 8 bit number, so it can be 0 - 255 

$result = []; 
$resIndex = 0; 

for ($i = 0; $i <= $a; $i++) { 
    // here is the heart of algorithm - it has cancer, but it should work 
    // by that cancer I mean calling three times pow isn't effective and I see other possible optimalisation, but I let it on you 
    if ((pow(2, $i) & $x) > 0) { 
     echo pow(2, $i) . "\n"; // prints "1", "2", "8", "16" 
     $result[$resIndex] = pow(2, $i); // save it to array for later use 
    } 
} 
+0

我需要的是數字和輸入任何超過2 n個添加劑,可以輸出數字 – Zhmchen

+0

我不能幫助自己,我仍然認爲你需要按位操作...檢查我添加的第二個例子,如果它是你想要什麼。 –

+0

我需要這個。第二個例子,如果我給你$ n2($ n2 = 2 + 8),我怎麼能得到2和8 – Zhmchen