【问题标题】:Determine if number is in the binary sequence 1 2 4 8 16 32 64 etc [duplicate]确定数字是否在二进制序列中 1 2 4 8 16 32 64 等 [重复]
【发布时间】:2025-12-28 18:35:06
【问题描述】:

可能重复:
How to check if a number is a power of 2

我想确定一个数字是否在

1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 ...

我试过这个:

public static void Main(string[] args)
{            
    int result = 1;  
    for (int i = 0; i < 15; i++)
    {          
        //Console.WriteLine(result);
        Console.WriteLine(result % 2);
        result *= 2;

    }  
}

As you can see 它返回 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...

我应该如何有效地将上述打印为0,包括1?

【问题讨论】:

  • 是的,我可以看到。有什么问题吗?
  • 我知道代码按预期工作。我的问题是编写什么代码来打印 期望的内容。
  • @CodeInChaos,我投票决定关闭它。感谢您的参考。
  • 对于一些琐碎的问题,经常有答案:www-graphics.stanford.edu/~seander/…

标签: c# .net math binary


【解决方案1】:

如果i 在您的序列中,则以下表达式应为真。

(i &amp; (i-1)) == 0)

http://rextester.com/JRH41036

【讨论】:

  • 这是一个非常有用的网站。
  • @zapthedingbat,是的。这正是我想要的。
【解决方案2】:

这样的事情怎么样?

bool IsInBinarySequence( int number ){
  var numbertocheck = 1;
  do{
if( number == numbertocheck ) return true;
numbertocheck *= 2;
  }while( numbertocheck <= number );
  return false;
}

这对要检查的数字没有具体限制,但会确保它停止检查要检查的数字是否大于我们试图确定是否在二进制序列中的实际数字。

【讨论】:

    【解决方案3】:

    由于第一次结果是奇数,你会得到1,因为之后你乘以2,你总是会得到0

    如果要获取 2 的幂列表,需要打印 result

    Console.WriteLine(result);
    

    一种原始的方法是:

    public static void Main(string[] args)
    {            
        int result = 1;  
        int numToCheck = 141234;
        boolean found = false;
        for (int i = 0; i < 15; i++)
        {          
            if (numToCheck == result) {
                found = true;
                break;
            }
            result *= 2;
        }  
        if(found) Console.WriteLine("Awesome");
    }
    

    【讨论】:

    • 我想要的只是确定result是否属于二进制序列1, 2, 4, 8
    • 他不想写我看起来的那个列表,而是想知道任何给定的数字是否是该序列的一部分,但考虑到他的代码,这很难理解。
    • 你就是这么做的。第一次运行的结果是 1,然后是 2,然后是 4,然后是 8,然后是 16,然后是 32,然后是 64,依此类推。
    • 如果要检查的数字大于2^15怎么办?
    • @ØyvindKnobloch-Bråthen - 这只是一个原始示例,我试图让这个想法清晰。不提供完整的实现。
    【解决方案4】:

    您可以使用以下方法确定一个数是否为 2 的幂(包括 2^0):

    public bool IsPowerOfTwo(int x) {
        return (x > 0) && ((x & (x - 1)) == 0)
    }
    

    Over here 你可以阅读为什么以及如何工作。

    【讨论】:

    • 糟糕,真的。我完全错了,会更新的。 ...完成。
    • 我会使用x&gt;=0,所以所有负数都会被拒绝。或者如果x&lt;0,则抛出ArgumentOutOfRangeException
    • @CodeInChaos 谢谢,已作相应修改。作为替代方案,您可以使用 uint 类型的参数。
    【解决方案5】:

    这有点小技巧,但这行得通……

        static void Main()
        {
            for (int i = 0; i < 40; i++)
            {
                var str = Convert.ToString(i, 2);
                var bitCount = str.Count(c => c == '1');
                Console.ForegroundColor = bitCount == 1 ? ConsoleColor.White : ConsoleColor.DarkGray;
                Console.WriteLine(i + ": " + (bitCount == 1));
            }
        }
    

    您似乎实际上是在询问数字的二进制表示中是否只有一位是 1

    【讨论】:

    • 为什么颜色会混入一个检查数字是否属于特定数字系列的方法中?
    • 因为这是一个示例,我认为它有助于突出显示何时满足条件
    • 我在这里似乎没有正确阅读。没有看到您设置控制台前景色。那么它似乎很好:)
    【解决方案6】:

    你不是测试数字是否在序列中但它是此类数字的生成器...只有打印部分包含某种测试...

    试试这个代码进行测试:

    public static void Main(string[] args)
    {            
        int result = 0;  
        int numToTest = 0;
        if ( int.TryParse (args[0], out numToTest) )
        {
           result = ((from c in Convert.ToString (numToTest, 2) where c == '1' select c).Count() == 1 ) ? 1 : 0;
        }
    
        Console.WriteLine(result);
    }
    

    上面的代码接受一个命令行参数,并根据您发布的标准测试它是否处于二进制序列中...如果是,则打印 1,否则打印 0。

    【讨论】:

    • 这似乎是一个很好的解决方案 :) +1
    【解决方案7】:

    没错。 1 0 0 0 0 0 是正确的顺序。 结果是第一个循环中的 1。 1% 2 是 1。 然后结果 *= 2 给出结果值 2。在下一个循环中运行 2 % 2 = 0。然后结果 *= 2 为 4。4%2 为 0。4 *= 2 为 8。8 %2 为 0。因为结果总是乘以 2,它保持在 2 行的幂中,因此 2 结果的 MOD 操作为 0。所以该代码一切正常。

    【讨论】:

      【解决方案8】:

      您的代码将只打印二进制序列。当您应用 MOD 2 时。所以你会得到 0 或 1 。所以它将以二进制序列打印。

      【讨论】:

        【解决方案9】:
        Boolean result = false;
        Int32 numberToTest = 64;
        Int32 limit = 15;
        
        for (int i = 0; i < limit && !result; i++)
        {
            if (Math.Pow(2, i).Equals(numberToTest))
            {
                result = true;
            }
        }
        
        Console.WriteLine(String.Format("Number {0} {1} a power of 2.", numberToTest, result ? "is" : "is not"));
        

        【讨论】:

          最近更新 更多