相关疑难解决方法(0)

如何检查数字是否为2的幂

今天我需要一个简单的算法来检查一个数是否是2的幂.

算法需要是:

  1. 简单
  2. 纠正任何ulong价值.

我想出了这个简单的算法:

private bool IsPowerOfTwo(ulong number)
{
    if (number == 0)
        return false;

    for (ulong power = 1; power > 0; power = power << 1)
    {
        // This for loop used shifting for powers of 2, meaning
        // that the value will become 0 after the last shift
        // (from binary 1000...0000 to 0000...0000) then, the 'for'
        // loop will break out.

        if (power == number)
            return true;
        if (power > number)
            return false; …
Run Code Online (Sandbox Code Playgroud)

c# algorithm math

549
推荐指数
13
解决办法
21万
查看次数

这个按位运算如何检查2的幂?

我正在看一些应该是微不足道的代码 - 但我的数学在这里惨遭失败.

这是一个条件,使用以下内容检查数字是否为2的幂:

if((num != 1) && (num & (num - 1))) { /* make num pow of 2 */ }
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何在num和num-1之间使用按位AND来确定数字是2的幂?

c math bit-manipulation

39
推荐指数
4
解决办法
7万
查看次数

标签 统计

math ×2

algorithm ×1

bit-manipulation ×1

c ×1

c# ×1