How to efficiently judge whether a number of numbers is 2
Question:
How to efficiently determine whether the given number of numbers is 2 without using floating -point operations or displacement operations?
Answer:
A simple and efficient algorithm is as follows:
Explanation:
<code class="language-c#">bool IsPowerOfTwo(ulong number) { return (number != 0) && ((number & (number - 1)) == 0); }</code>
Example:
Consider numbers 8 (binary 1000). Subtract 1 to get 7 (binary 0111). It only has one bit and 7 sets of 1.8 and 7, which indicates that 8 is the power of 2.
Note:
The above algorithm returns True to 0, and 0 is not the power of 2. If you want to exclude 0, you can modify the algorithm as follows:
The above is the detailed content of How to Efficiently Determine if a Number is a Power of 2?. For more information, please follow other related articles on the PHP Chinese website!