Home >Backend Development >C++ >How to Efficiently Determine if a Number is a Power of 2?
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>bit and the component (&) comparison of each digit, if both digits are 1, return 1, otherwise 0. By minusing 1 from the number, we create a binary number, the minimum effective position (the bit set in the original number to 1) is set to 1. If the original number is the power of 2, the minus 1 will remove all the positions on the right side of the highest setting position, so that the result of the operation and the operation is 0. On the contrary, if the original number is not a power of 2, after 1 subtraction, the binary representation of the number will be set at least two bit to 1, which will cause the result and the operation to result in non -zero value.
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!