[英]calculating number of consecutive ones in a binary number using c#
我想讓程序遍歷從00000000到11111111的每個可能的二進制數,並計算出連續的“運行次數”。 例如)00000001和11100000都計為一次的運行00001010和11101110都計為兩次的運行
問題是,它忽略了AND遮罩部分,我不知道為什么。
{
static void Main(string[] args)
{
//Start
int stuff = BitRunner8();
//Display
Console.Write(stuff);
Console.ReadKey();
}
public static int BitRunner8()
{
int uniRunOrNot = 0;
int uniRunCount = 0;
int uniRunTotal = 0;
//iterating from numbers 0 to 255
for (int x = 0; x < 255; x++)
{
//I use 128 as my AND mask because 128 is 10000000 in binary
for ( int uniMask = 128; uniMask != 0; uniMask >>= 1)
{
//This is the if statement that doesn't return true ever
if ((x & uniMask) != 0)
{
//If the and mask is true, and ther were no previous ones before it, add to the the uniRunCount
if (uniRunOrNot == 0)
{
//Total count of the runs
uniRunCount++;
}
// Making it so that if two consective ones are in a row, the 'if' statement right above would return false,
//so that it wouldn't add to the uniRunCount
uniRunOrNot++;
}
else
{
//add the total number of runs to uniRunTotal, and then reset both uniRunOrNot, and uniRunCount
uniRunTotal += uniRunCount;
uniRunOrNot = uniRunCount = 0;
}
}
}
//Divide the final amount by 256 total numbers
uniRunTotal /= 256;
return uniRunCount;
}
}
問題是您的代碼將忽略包含最低有效位的運行。 您的代碼僅在發現零位時更新uniRunTotal
。 當最低有效位不為零時, uniRunCount
永遠不會添加到總數中。
在循環之后添加代碼以添加uniRunCount
來解決此問題。
您還可以通過應用哨兵策略來解決此問題:計數另一端的位數,並使用9位而不是8位,因為位數9始終為零:
for (int uniMask = 1; uniMask <= 256; uniMask <<= 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.