ChatGPT解决这个技术问题 Extra ChatGPT

如何检查一个数字是否是2的幂

今天我需要一个简单的算法来检查一个数字是否是 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;
    }
    return false;
}

但后来我想:如何检查 log2 x 是否是一个整数?当我检查 2^63+1 时,由于四舍五入,Math.Log() 返回正好 63。所以我检查了 2 的 63 次方是否等于原始数字,因为计算是在 doubles 中完成的,而不是精确的数字。

private bool IsPowerOfTwo_2(ulong number)
{
    double log = Math.Log(number, 2);
    double pow = Math.Pow(2, Math.Round(log));
    return pow == number;
}

这为给定的错误值返回了 true9223372036854775809

有更好的算法吗?

我认为当 X 是 2 的幂的和(例如 8 + 16)时,解决方案 (x & (x - 1)) 可能会返回误报。
所有数字都可以写成 2 的幂的和,这就是为什么我们可以用二进制表示任何数字。此外,您的示例不会返回误报,因为 11000 & 10111 = 10000 != 0。
@JoeBrown 它没有任何误报。实际上,该表达式返回任何两个 2 的幂之和中的较大者。
现在在 .net 6 中非常容易stackoverflow.com/a/69711480/6527049

M
Marco Bonelli

这个问题有一个简单的技巧:

bool IsPowerOfTwo(ulong x)
{
    return (x & (x - 1)) == 0;
}

请注意,此函数将为 0 报告 true,这不是 2 的幂。如果你想排除它,方法如下:

bool IsPowerOfTwo(ulong x)
{
    return (x != 0) && ((x & (x - 1)) == 0);
}

解释

首先是 MSDN 定义中的按位二进制 & 运算符:

二进制 & 运算符是为整数类型和 bool 预定义的。对于整数类型, & 计算其操作数的逻辑按位与。对于 bool 操作数, & 计算其操作数的逻辑与;也就是说,当且仅当它的两个操作数都为真时,结果才为真。

现在让我们看看这一切是如何发生的:

该函数返回布尔值 (true / false) 并接受一个 unsigned long 类型的传入参数(在本例中为 x)。为简单起见,让我们假设有人传递了值 4 并像这样调用函数:

bool b = IsPowerOfTwo(4)

现在我们用 4 替换每次出现的 x:

return (4 != 0) && ((4 & (4-1)) == 0);

好吧,我们已经知道 4 != 0 评估为真,到目前为止一切都很好。但是关于:

((4 & (4-1)) == 0)

这当然转化为:

((4 & 3) == 0)

但是 4&3 到底是什么?

4 的二进制表示是 100,3 的二进制表示是 011(记住 & 采用这些数字的二进制表示)。所以我们有:

100 = 4
011 = 3

想象一下这些值就像基本加法一样堆叠起来。 & 运算符表示如果两个值都等于 1,则结果为 1,否则为 0。所以 1 & 1 = 11 & 0 = 00 & 0 = 00 & 1 = 0。所以我们做数学:

100
011
----
000

结果只是 0。所以我们回过头来看看我们的 return 语句现在翻译成什么:

return (4 != 0) && ((4 & 3) == 0);

现在翻译为:

return true && (0 == 0);
return true && true;

我们都知道 true && true 只是 true,这表明对于我们的示例,4 是 2 的幂。


@Kripp:该数字将采用二进制形式 1000...000。当您对其进行 -1 时,它将采用 0111...111 的形式。因此,这两个数字的二进制结果是 000000。这不会发生在非二次方的情况下,因为例如 1010100 将变为 1010011,从而导致(继续...)
...导致二进制和之后的1010000。唯一的误报是 0,这就是我要使用的原因: return (x != 0) && ((x & (x - 1)) == 0);
克里普,考虑 (2:1, 10:1) (4:3, 100:11) (8:7, 1000:111) (16:15, 10000:1111) 看到模式了吗?
@ShuggyCoUk:二进制补码是负数的表示方式。由于这是一个无符号整数,负数的表示是不相关的。该技术仅依赖于非负整数的二进制表示。
@SoapBox - 更常见的是什么?不是二的幂的零或非零数字?这是一个没有更多上下文就无法回答的问题。无论如何,这真的,真的无关紧要。
c
chqrlie

一些记录和解释这个和其他一些小技巧的网站是:

http://graphics.stanford.edu/~seander/bithacks.html (http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2)

http://bits.stephan-brumme.com/ (http://bits.stephan-brumme.com/isPowerOfTwo.html)

还有他们的祖父,the book "Hacker's Delight" by Henry Warren, Jr.

http://www.hackersdelight.org/

正如 Sean Anderson's page 所解释的,表达式 ((x & (x - 1)) == 0) 错误地表明 0 是 2 的幂。他建议使用:

(!(x & (x - 1)) && x)

来纠正这个问题。


0 是 2 的幂... 2 ^ -inf = 0。;) ;) ;)
由于这是一个带有 C# 标记的线程,因此值得指出的是,最后一个表达式(Sean Anderson 的)在 C# 中是非法的,因为 ! 只能应用于布尔值类型,并且 && 还要求两个操作数都是布尔值 - (除了用户定义的运算符使其他事情成为可能,但这与 ulong 无关。)
catonmat.net/low-level-bit-hacks 通过 8 位示例解释了一些相关的 bithack。例如,用 y = x & (-x) 隔离最右边的 1 位。该测试只是清除最低设置位的一种特殊情况。
A
Andreas Petersson

return (i & -i) == i


任何提示为什么这会或不会起作用?我只在 java 中检查了它的正确性,那里只有签名的整数/长整数。如果它是正确的,这将是更好的答案。更快+更小
它利用了二进制补码表示法的一个特性:计算一个数字的负值,您执行按位否定并将结果加 1。设置的 i 的最低有效位也将设置在 -i 中。其下方的位将为 0(在两个值中),而其上方的位将相互反转。因此,i & -i 的值将是 i 中的最低有效设置位(它是 2 的幂)。如果 i 具有相同的值,那么这是唯一设置的位。当 i 为 0 时它会失败,原因与 i & (i - 1) == 0 相同。
如果 i 是无符号类型,则二进制补码与它无关。您只是在利用模运算和按位与的属性。
如果是 i==0(返回 (0&0==0),即 true),则此方法不起作用。它应该是 return i && ( (i&-i)==i )
M
Matt Howells
bool IsPowerOfTwo(ulong x)
{
    return x > 0 && (x & (x - 1)) == 0;
}

这个解决方案更好,因为如果负数能够传入,它也可以处理负数。(如果 long 而不是 ulong)
在这种情况下,为什么小数会作为 2 的幂传递?
d
displayName

已接受答案的以下附录可能对某些人有用:

以二进制表示时,2 的幂总是看起来像 1 后跟 n 个零,其中 n 大于或等于 0。例如:

Decimal  Binary
1        1     (1 followed by 0 zero)
2        10    (1 followed by 1 zero)
4        100   (1 followed by 2 zeroes)
8        1000  (1 followed by 3 zeroes)
.        .
.        .
.        .

等等。

当我们从这些数字中减去 1 时,它们变为 0 后跟 n 个 1,并且 n 再次与上述相同。前任:

Decimal    Binary
1 - 1 = 0  0    (0 followed by 0 one)
2 - 1 = 1  01   (0 followed by 1 one)
4 - 1 = 3  011  (0 followed by 2 ones)
8 - 1 = 7  0111 (0 followed by 3 ones)
.          .
.          .
.          .

等等。

来到症结所在

当我们对数字 x(2 的幂)和 x - 1 进行按位与运算时会发生什么?

x 的一个与 x - 1 的零对齐,并且 x 的所有零与 x - 1 的一个对齐,导致按位与结果为 0。就是我们如何使上面提到的单行答案是正确的。

进一步增加了上述公认答案的美感-

所以,我们现在有一个财产可供我们使用:

当我们从任何数字中减去 1 时,在二进制表示中,最右边的 1 将变为 0,而最右边的 1 左侧的所有零现在都将变为 1。

这个属性的一个很棒的用途是找出 - 给定数字的二进制表示中存在多少个 1? 对给定整数 x 执行此操作的简短代码是:

byte count = 0;
for ( ; x != 0; x &= (x - 1)) count++;
Console.Write("Total ones in the binary representation of x = {0}", count);

可以从上面解释的概念证明的数字的另一个方面是“每个正数都可以表示为 2 的幂的和吗?”。

是的,每个正数都可以表示为 2 的幂的总和。对于任何数字,取其二进制表示。例如:取数 117

The binary representation of 117 is 1110101

Because  1110101 = 1000000 + 100000 + 10000 + 0000 + 100 + 00 + 1
we have  117     = 64      + 32     + 16    + 0    + 4   + 0  + 1

@Michi:我是否在某处声称 0 是一个正数?还是2的幂?
是的,以 0 为例,并在二进制表示中对其进行数学运算。它造成了混乱。
P
Peter Mortensen

这是一个简单的 C++ 解决方案:

bool IsPowerOfTwo( unsigned int i )
{
    return std::bitset<32>(i).count() == 1;
}

在 gcc 上,它编译成一个名为 __builtin_popcount 的 gcc 内置函数。不幸的是,一个处理器系列还没有一条汇编指令来执行此操作(x86),因此它是最快的位计数方法。在任何其他架构上,这是一条汇编指令。
@deft_code 较新的 x86 微架构支持 popcnt
实现 i & (i-1) == 0lea eax, [rdi-1] + test/jnzpopcnt / cmp/je 便宜一些,特别是如果您不需要将 i==0 情况视为不计算在内。
感谢您提及 C++ 并将其链接到 C++ 的维基百科页面。如果没有它,那真的会很混乱。 /s
c
configurator

发布问题后,我想到了以下解决方案:

我们需要检查其中一个二进制数字是否恰好是一。因此,我们只需将数字一次右移一位,如果等于 1,则返回 true。如果在任何时候我们得到一个奇数 ((number & 1) == 1),我们就知道结果是 false。这证明(使用基准)比(大)真值的原始方法略快,而对于假或小值则快得多。

private static bool IsPowerOfTwo(ulong number)
{
    while (number != 0)
    {
        if (number == 1)
            return true;

        if ((number & 1) == 1)
            // number is an odd number and not 1 - so it's not a power of two.
            return false;

        number = number >> 1;
    }
    return false;
}

当然,Greg 的解决方案要好得多。


R
Rezo Megrelidze
    bool IsPowerOfTwo(int n)
    {
        if (n > 1)
        {
            while (n%2 == 0)
            {
                n >>= 1;
            }
        }
        return n == 1;
    }

这是一个通用算法,用于确定一个数字是否是另一个数字的幂。

    bool IsPowerOf(int n,int b)
    {
        if (n > 1)
        {
            while (n % b == 0)
            {
                n /= b;
            }
        }
        return n == 1;
    }

a
abelenky
bool isPow2 = ((x & ~(x-1))==x)? !!x : 0;

这是c#吗?我猜这是 c++,因为 x 作为布尔值返回。
我确实把它写成C++。让它 C# 是微不足道的: bool isPow2 = ((x & ~(x-1))==x)? x!=0:假;
b
bugs king
bool isPowerOfTwo(int x_)
{
  register int bitpos, bitpos2;
  asm ("bsrl %1,%0": "+r" (bitpos):"rm" (x_));
  asm ("bsfl %1,%0": "+r" (bitpos2):"rm" (x_));
  return bitpos > 0 && bitpos == bitpos2;
}

如果您尝试排除 x_ == 0,则 bitpos > 0 不是有意义的测试。 x_ = 1 的输入有一个设置位,并导致 BSF 和 BSR 产生一个位位置结果 0。您没有初始化您的 "+r" 读写输出,因此您没有任何保证 x_ == 0 的行为。 (BSF 和 BSR 在 input=0 时保持目的地未修改;AMD 记录了这一点,Intel 实现了它,但只将结果记录为未定义的值。)也许 asm 语句之前的 bitpos = 0bitpos2 = 32 会很有用,所以它们不匹配在输入 = 0。
我还建议从输入约束中删除 "m"。您希望编译器选择一个寄存器,因为您要读取它两次。第二个 asm 语句可能会被安排为 output=input 最初,因此编译器可以根据需要选择相同的寄存器用于输入和输出。
S
Stephan Bauer
int isPowerOfTwo(unsigned int x)
{
    return ((x != 0) && ((x & (~x + 1)) == x));
}

这真的很快。检查所有 2^32 个整数大约需要 6 分 43 秒。


P
Peter Mortensen
return ((x != 0) && !(x & (x - 1)));

如果 x 是 2 的幂,则其唯一的 1 位位于 n 位置。这意味着 x – 1 在位置 n 有一个 0。要了解原因,请回想二进制减法的工作原理。当 x 减 1 时,借位一直传播到位置 n;位 n 变为 0,所有低位变为 1。现在,由于 xx – 1 没有共同的 1 位,x & (x – 1) 为 0,!(x & (x – 1)) 为真。


F
FReeze FRancis

对于 2 的任何幂,以下也成立。

n&(-n)==n

注意: n=0 失败,因此需要检查它的原因是:-n 是 n 的 2s 补码。 -n 将与 n 相比,将 n 的最右边设置位左侧的每一位翻转。对于 2 的幂,只有一个设置位。


这个答案是 posted 7 年前。
B
Bastien Léonard

查找给定数字是否为 2 的幂。

#include <math.h>

int main(void)
{
    int n,logval,powval;
    printf("Enter a number to find whether it is s power of 2\n");
    scanf("%d",&n);
    logval=log(n)/log(2);
    powval=pow(2,logval);

    if(powval==n)
        printf("The number is a power of 2");
    else
        printf("The number is not a power of 2");

    getch();
    return 0;
}

或者,在 C# 中: return x == Math.Pow(2, Math.Log(x, 2));
破碎的。遭受主要的浮点舍入问题。如果您想使用浮点数,请使用 frexp 而不是讨厌的 log 东西。
j
jerrymouse

如果一个数字仅包含 1 个设置位,则它是 2 的幂。我们可以使用这个属性和通用函数 countSetBits 来确定一个数字是否是 2 的幂。

这是一个 C++ 程序:

int countSetBits(int n)
{
        int c = 0;
        while(n)
        {
                c += 1;
                n  = n & (n-1);
        }
        return c;
}

bool isPowerOfTwo(int n)
{        
        return (countSetBits(n)==1);
}
int main()
{
    int i, val[] = {0,1,2,3,4,5,15,16,22,32,38,64,70};
    for(i=0; i<sizeof(val)/sizeof(val[0]); i++)
        printf("Num:%d\tSet Bits:%d\t is power of two: %d\n",val[i], countSetBits(val[i]), isPowerOfTwo(val[i]));
    return 0;
}

我们不需要明确检查 0 是否是 2 的幂,因为它也会为 0 返回 False。

输出

Num:0   Set Bits:0   is power of two: 0
Num:1   Set Bits:1   is power of two: 1
Num:2   Set Bits:1   is power of two: 1
Num:3   Set Bits:2   is power of two: 0
Num:4   Set Bits:1   is power of two: 1
Num:5   Set Bits:2   is power of two: 0
Num:15  Set Bits:4   is power of two: 0
Num:16  Set Bits:1   is power of two: 1
Num:22  Set Bits:3   is power of two: 0
Num:32  Set Bits:1   is power of two: 1
Num:38  Set Bits:3   is power of two: 0
Num:64  Set Bits:1   is power of two: 1
Num:70  Set Bits:3   is power of two: 0

当函数的返回类型为“ulong”时,将 c 作为“int”返回?使用 while 而不是 if?我个人看不出原因,但它似乎有效。编辑: - 不......它会为任何大于 0 的东西返回 1!?
@JamesKhoury 我正在编写一个 c++ 程序,所以我错误地返回了一个 int。然而,这是一个小错别字,不值得投反对票。但我不明白你评论的其余部分“使用while而不是if”和“它会为大于0的任何东西返回1”的原因。我添加了主存根来检查输出。 AFAIK它的预期输出。如果我错了,请纠正我。
C
Chethan

这是我设计的另一种方法,在这种情况下使用 | 而不是 &

bool is_power_of_2(ulong x) {
    if(x ==  (1 << (sizeof(ulong)*8 -1) ) return true;
    return (x > 0) && (x<<1 == (x|(x-1)) +1));
}

您需要这里的 (x > 0) 位吗?
@configurator,是的,否则 is_power_of_2(0) 将返回 true
v
vivek nuna

现在在 .Net 6 中非常容易。

using System.Numerics;

bool isPow2 = BitOperations.IsPow2(64); // sets true

Here 是文档。


K
Khaled.K

例子

0000 0001    Yes
0001 0001    No

算法

使用位掩码,将变量 NUM 除以二进制 IF R > 0 AND L > 0:返回 FALSE 否则,NUM 变为非零值 IF NUM = 1:返回 TRUE 否则,转到步骤 1

复杂

时间 ~ O(log(d)) 其中 d 是二进制位数


U
Uche Igbokwe

.NET 6 中有一个衬里

// IsPow2 evaluates whether the specified Int32 value is a power of two.
Console.WriteLine(BitOperations.IsPow2(128));            // True

r
rhodan

改进@user134548 的答案,无需位算术:

public static bool IsPowerOfTwo(ulong n)
{
    if (n % 2 != 0) return false;  // is odd (can't be power of 2)

    double exp = Math.Log(n, 2);
    if (exp != Math.Floor(exp)) return false;  // if exp is not integer, n can't be power
    return Math.Pow(2, exp) == n;
}

这适用于:

IsPowerOfTwo(9223372036854775809)

浮点运算比简单的按位表达式慢得多
j
jbat100

如果您有 .NET Core 3,Mark Gravell 建议使用 thisSystem.Runtime.Intrinsics.X86.Popcnt.PopCount

public bool IsPowerOfTwo(uint i)
{
    return Popcnt.PopCount(i) == 1
}

单条指令,比 (x != 0) && ((x & (x - 1)) == 0) 快,但可移植性较差。


你确定它比 (x != 0) && ((x & (x - 1)) == 0) 快吗?我对此表示怀疑,尤其是。在 popcnt 不可用的旧系统上
这不是更快。我刚刚在现代英特尔 CPU 上对此进行了测试,并验证了反汇编中使用的 POPCNT(在 C 代码中,而不是 .NET 中授予)。 POPCNT 通常对位计数更快,但对于单个位打开的情况,位旋转技巧仍然快 10%。
哎呀,我收回了。我正在循环测试我是否认为分支预测是“作弊”。 POPCNT 确实是在单个时钟周期内运行的单条指令,如果你有它,它会更快。
A
ABHISHEK PARMAR

在这种方法中,您可以检查整数中是否只有 1 个设置位并且整数 > 0 (c++)。

bool is_pow_of_2(int n){
    int count = 0;
    for(int i = 0; i < 32; i++){
        count += (n>>i & 1);
    }
    return count == 1 && n > 0;
}


e
eraoul

在 C 语言中,我测试了 i && !(i & (i - 1) 技巧并将其与 __builtin_popcount(i) 进行了比较,在 Linux 上使用 gcc 并带有 -mpopcnt 标志以确保使用 CPU 的 POPCNT 指令。我的测试程序计算了 0 到 2^31 之间的整数个数,它们是 2 的幂。

起初我认为 i && !(i & (i - 1) 快了 10%,尽管我验证了 POPCNT 在我使用的反汇编中使用了__builtin_popcount

然而,我意识到我已经包含了一个 if 语句,并且分支预测在 bit twiddling 版本上可能做得更好。正如预期的那样,我删除了 if 并且 POPCNT 最终更快。

结果:

Intel(R) Core(TM) i7-4771 CPU 最高 3.90GHz

Timing (i & !(i & (i - 1))) trick
30

real    0m13.804s
user    0m13.799s
sys     0m0.000s

Timing POPCNT
30

real    0m11.916s
user    0m11.916s
sys     0m0.000s

AMD Ryzen Threadripper 2950X 16 核处理器最高 3.50GHz

Timing (i && !(i & (i - 1))) trick
30

real    0m13.675s
user    0m13.673s
sys 0m0.000s

Timing POPCNT
30

real    0m13.156s
user    0m13.153s
sys 0m0.000s

请注意,这里的 Intel CPU 似乎比 AMD 稍微慢一点,但 POPCNT 快得多; AMD POPCNT 没有提供那么多的提升。

popcnt_test.c:

#include "stdio.h"

// Count # of integers that are powers of 2 up to 2^31;
int main() {
  int n;
  for (int z = 0; z < 20; z++){
      n = 0;
      for (unsigned long i = 0; i < 1<<30; i++) {
       #ifdef USE_POPCNT
        n += (__builtin_popcount(i)==1); // Was: if (__builtin_popcount(i) == 1) n++;
       #else
        n += (i && !(i & (i - 1)));  // Was: if (i && !(i & (i - 1))) n++;
       #endif
      }
  }

  printf("%d\n", n);
  return 0;
}

运行测试:

gcc popcnt_test.c -O3 -o test.exe
gcc popcnt_test.c -O3 -DUSE_POPCNT -mpopcnt -o test-popcnt.exe

echo "Timing (i && !(i & (i - 1))) trick"
time ./test.exe

echo
echo "Timing POPCNT"
time ./test-opt.exe

A
Anil Gupta

我看到很多答案都建议返回 n && !(n & (n - 1)) 但根据我的经验,如果输入值为负数,它会返回错误值。我将在这里分享另一种简单的方法,因为我们知道两个数字的幂只有一个设置位,所以我们将简单地计算设置位的数量,这将花费 O(log N) 时间。

while (n > 0) {
    int count = 0;
    n = n & (n - 1);
    count++;
}
return count == 1;

查看这篇文章到count no. of set bits


M
Marcus Moo

这也是另一种方法

package javacore;

import java.util.Scanner;

public class Main_exercise5 {
    public static void main(String[] args) {
        // Local Declaration
        boolean ispoweroftwo = false;
        int n;
        Scanner input = new Scanner (System.in);
        System.out.println("Enter a number");
        n = input.nextInt();
        ispoweroftwo = checkNumber(n);
        System.out.println(ispoweroftwo);
    }
    
    public static boolean checkNumber(int n) {
        // Function declaration
        boolean ispoweroftwo= false;
        // if not divisible by 2, means isnotpoweroftwo
        if(n%2!=0){
            ispoweroftwo=false;
            return ispoweroftwo;
        }
        else {
            for(int power=1; power>0; power=power<<1) {
                if (power==n) {
                    return true;
                }
                else if (power>n) {
                    return false;
                }
            }
        }
        return ispoweroftwo;
    }
}

A
Aleksandar Biševac

如果数字是最多 64 值的 2 的幂(您可以在 for 循环条件中更改它(“6”表示 2^6 是 64),则返回此值;

const isPowerOfTwo = (number) => { 让结果 = false; for (let i = 1; i <= 6; i++) { if (number === Math.pow(2, i)) { result = true; } } 返回结果; }; console.log(isPowerOfTwo(16)); console.log(isPowerOfTwo(10));


v
velocity

我一直在阅读 Random.nextInt(int bound) 的 documentation 并看到了这段很好的代码,它检查参数是否是 2 的幂,它说(部分代码):

if ((bound & -bound) == bound) // ie, bouns is a power of 2   

让我们测试一下

for (int i=0; i<=8; i++) {
  System.out.println(i+" = " + Integer.toBinaryString(i));
}

>>
0 = 0
1 = 1
2 = 10
3 = 11
4 = 100
5 = 101
6 = 110
7 = 111
8 = 1000
// the left most 0 bits where cut out of the output

for (int i=-1; i>=-8; i--) {
  System.out.println(i+" = " + Integer.toBinaryString(i));
}

>>
-1 = 11111111111111111111111111111111
-2 = 11111111111111111111111111111110
-3 = 11111111111111111111111111111101
-4 = 11111111111111111111111111111100
-5 = 11111111111111111111111111111011
-6 = 11111111111111111111111111111010
-7 = 11111111111111111111111111111001
-8 = 11111111111111111111111111111000

你注意到什么了吗?幂 2 数在正和负二进制表示中具有相同的位,如果我们进行逻辑与我们得到相同的数字:)

for (int i=0; i<=8; i++) {
  System.out.println(i + " & " + (-i)+" = " + (i & (-i)));
}

>>
0 & 0 = 0
1 & -1 = 1
2 & -2 = 2
3 & -3 = 1
4 & -4 = 4
5 & -5 = 1
6 & -6 = 2
7 & -7 = 1
8 & -8 = 8

D
Dr.jacky

科特林:

fun isPowerOfTwo(n: Int): Boolean {
    return (n > 0) && (n.and(n-1) == 0)
}

或者

fun isPowerOfTwo(n: Int): Boolean {
    if (n == 0) return false
    return (n and (n - 1).inv()) == n
}

inv 反转此值中的位。

注意:log2 解决方案不适用于大量数字,例如 536870912 ->

import kotlin.math.truncate
import kotlin.math.log2

fun isPowerOfTwo(n: Int): Boolean {
    return (n > 0) && (log2(n.toDouble())) == truncate(log2(n.toDouble()))
}

W
WaterGenie

有许多答案和发布的链接解释了为什么 n & (n-1) == 0 适用于 2 的幂,但我找不到任何解释为什么它不适用于非 2 的幂,所以我添加这个只是为了完整性。

对于 n = 1 (2^0 = 1),1 & 0 = 0,所以我们很好。

对于奇数 n > 1,至少有2位1(最左边和最右边的位)。现在 n 和 n-1 只会在最右边的位上有所不同,因此它们的 &-sum 在最左边的位上至少有一个 1,所以 n & (n-1) != 0

n:          1xxxx1  for odd n > 1
n-1:        1xxxx0
            ------
n & (n-1):  1xxxx0 != 0

现在即使 n 不是 2 的幂,我们也至少有 2 位 1(最左边和非最右边)。在这里,n 和 n-1 的最右边的 1 位不同,因此它们的 &-sum 在最左边的位也至少有一个 1:

        right-most 1 bit of n
                 v
n:          1xxxx100..00 for even n
n-1:        1xxxx011..11
            ------------
n & (n-1):  1xxxx000..00 != 0

u
user134548
private static bool IsPowerOfTwo(ulong x)
{
    var l = Math.Log(x, 2);
    return (l == Math.Floor(l));
}

试试这个号码 9223372036854775809。它有效吗?我认为不会,因为舍入错误。
@configurator 922337203685477580_9_ 在我看来不像 2 的幂;)
@Kirschstein:这个数字给了他一个误报。
Kirschstein:在我看来也不是一个。虽然它看起来确实像一个功能......