相关疑难解决方法(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万
查看次数

检查整数内是否只设置了一个位(无论其位置如何)

我使用64位整数内的位存储标志.
我想知道是否有一个位设置无论64位整数内的位置(ei我不关心任何特定位的位置).

boolean isOneSingleBitSet (long integer64)
{
   return ....;
}
Run Code Online (Sandbox Code Playgroud)

我可以使用Bit Twiddling Hacks(Sean Eron Anderson)计算位数,但我想知道检测单个位是否设置的最有效方法是什么...

我发现了一些其他相关的问题:

以及一些维基百科页面:

注意:我的应用程序是在java中,但我很好奇使用其他语言的优化...


编辑:琉永福指出我的问题在我的第一个链接已经得到了答案:请参见如果一个整数是2的幂确定位操作黑客(肖恩·安德森玉龙).我没有意识到单个位与2的幂相同.

java binary bit-manipulation bit bitwise-operators

7
推荐指数
2
解决办法
9461
查看次数

标签 统计

algorithm ×1

binary ×1

bit ×1

bit-manipulation ×1

bitwise-operators ×1

c# ×1

java ×1

math ×1