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

23
推荐指数
2
解决办法
3万
查看次数

为什么 n &amp; (n - 1) 总是从 n 中清除 1 位?

给定一个数字n,逐位运算n & (n - 1)总是产生一个距离 1 位的数字n。以下是一些示例:

n = 4 => b'100' & b'011' = b'000'
n = 5 => b'101' & b'100' = b'100'
n = 6 => b'110' & b'101' = b'100' 
Run Code Online (Sandbox Code Playgroud)

换句话说,n & (n - 1)总是从 中清除 1 位n。为什么是这样?有人可以提供证明吗?

bit-manipulation

2
推荐指数
1
解决办法
813
查看次数

标签 统计

algorithm ×1

bit-manipulation ×1

c ×1

c# ×1

math ×1