我想測試一個正整數來查看它的二進制表示是否以零或多個1開始,然後是一個或多個0。驗證大整數的二進制模式(BigInteger)
00000000 // Valid
10000000 // Valid
11000000 // Valid
11100000 // Valid
11110000 // Valid
11111100 // Valid
11111110 // Valid
11111110 // Valid
11111111 // Not Valid
// Any other combination is Not Valid
表達式與正則表達式相同將是^ [1] * [0] + $。當然,這只是爲了澄清,我們不能使用正則表達式。
的蠻力方法:
- 創建多個位掩碼,共同確定的結果。
- 用動態掩碼循環顯示每個數字以確定結果。
問題是我正在處理巨大的正整數,它可能有數十萬個數字,並且需要爲數千個這樣的數字執行此測試。
是否有更有效的方法來確定這種二進制模式?
UPDATE
這裏是我試過的實現。還沒有比較時間與其他答案。
public static bool IsDiagonalToPowerOfTwo (this System.Numerics.BigInteger number)
{
byte [] bytes = null;
bool moreOnesPossible = true;
if (number == 0) // 00000000
{
return (true); // All bits are zero.
}
else
{
bytes = number.ToByteArray();
if ((bytes [bytes.Length - 1] & 1) == 1)
{
return (false);
}
else
{
for (byte b=0; b < bytes.Length; b++)
{
if (moreOnesPossible)
{
if (bytes [b] == 255)
{
// Continue.
}
else if
(
((bytes [b] & 128) == 128) // 10000000
|| ((bytes [b] & 192) == 192) // 11000000
|| ((bytes [b] & 224) == 224) // 11100000
|| ((bytes [b] & 240) == 240) // 11110000
|| ((bytes [b] & 248) == 248) // 11111000
|| ((bytes [b] & 252) == 252) // 11111100
|| ((bytes [b] & 254) == 254) // 11111110
)
{
moreOnesPossible = false;
}
else
{
return (false);
}
}
else
{
if (bytes [b] > 0)
{
return (false);
}
}
}
}
}
return (true);
}
你實際上是在使用它們*作爲整數*,還是就像位存儲一樣?坦率地說,如果這些是唯一有效的集合,我會使用不同的表示法,即。 「數量,零的數量」。當然,如果你需要做算術不工作等 – 2012-08-05 15:59:40
http://graphics.stanford.edu/~seander/bithacks.html – 2012-08-05 16:09:42
我不知道什麼是HUME大整數,這是如何表示的。淨?我想數組的ubyte/uint/etc ......是這樣嗎? @MarcGravell已經問過,但是,你是用這些數據做一些算術還是隻是一種表示? – devundef 2012-08-05 16:25:00