Determine whether a number of numbers is 2
Determine whether the given number is the power of 2, which requires a simple and accurate algorithm. The author proposes two algorithms, but encountered the problem when using the calculation of numbers.
The first algorithm
The first algorithm Use a simple cycle to check the power of 2 through the displacement:
This method is simple and easy to understand, and it can run perfectly for any IsPowerOfTwo
value.
<code class="language-c#">private bool IsPowerOfTwo(ulong number) { if (number == 0) return false; for (ulong power = 1; power > 0; power = power << 1) { if (power == number) return true; if (power > number) return false; } return false; }</code>
ulong
However, due to the problem of discarding, this algorithm cannot be properly handled 9223372036854775809.
The improved algorithm IsPowerOfTwo_2
<code class="language-c#">private bool IsPowerOfTwo_2(ulong number) { double log = Math.Log(number, 2); double pow = Math.Pow(2, Math.Round(log)); return pow == number; }</code>
Algorithm explanation
This improved algorithm cleverly uses the bit operation:
<code class="language-c#">bool IsPowerOfTwo(ulong x) { return (x & (x - 1)) == 0; }</code>
Subtract 1 from the number to turn all 1 to 0, and turn all 0 to 1.
If the number is the power of 2, the binary indicates that there will be only one digit.When the number and (x -1) are performed and the operation, all the bit except 1 on the far right will be 0.
&
The above is the detailed content of How Can We Efficiently Determine if a Number is a Power of 2?. For more information, please follow other related articles on the PHP Chinese website!