Whether the number of numerals is 2 is the power of 2
The code is simple and clear.
A method to solve this problem is to iterate 2 continuous power, check whether any power -in -one matches the input number. This can be implemented as follows: Method 2: The number of calculation algorithms
Another method involves the calculation of the use of the number of pairs. However, this requires caution because floating -point calculations may cause accuracy. Consider the following code:
<code class="language-c#">private bool IsPowerOfTwo(ulong number) { if (number == 0) return false; for (ulong power = 1; power > 0; power <<= 1) { if (power == number) return true; if (power > number) return false; } return false; }</code>
The optimal solution: bit computing method More effective solutions are the use of bit operations. The power of 2 has a unique characteristic: when the (X -1) is performed and the operation (&), the result value is always 0. This attribute can be expressed as follows:
In order to eliminate the candidate of the power of zero as 2, it can be modified slightly:
<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>
This method provides an efficient and direct solution to determine whether the number is 2.
<code class="language-c#">bool IsPowerOfTwo(ulong x) { return (x & (x - 1)) == 0; }</code>
The above is the detailed content of Is a Number a Power of 2? How Can We Efficiently Determine This?. For more information, please follow other related articles on the PHP Chinese website!