使用c#计算二进制数中连续一的个数

本文关键字:连续 计算 二进制数 使用 | 更新日期: 2023-09-27 18:12:17

我想让程序遍历从00000000到11111111的所有可能的二进制数,并计算连续"运行"1的次数。例如:00000001和11100000都算作单次运行00001010和11101110都算两次1

问题是,它忽略了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;
    }
}

使用c#计算二进制数中连续一的个数

问题是您的代码忽略了包含最低有效位的运行。您的代码仅在发现零位时更新uniRunTotal。当最低有效位不为零时,uniRunCount不加到总数中。

在循环后添加代码以添加uniRunCount来解决此问题。

您还可以通过应用哨兵策略来解决此问题:从另一端计数位,并使用9位而不是8位,因为第9位总是零:

for (int uniMask = 1; uniMask <= 256; uniMask <<= 1)