Home >Backend Development >C++ >Is a Number a Power of 2? A Bitwise Approach
The power to judge whether the number is 2 is 2
Judging whether a number of numbers is 2 requires an efficient and accurate algorithm. This article introduces an algorithm based on bit operations:
This algorithm uses the position and the operational symbol (&), which compares the binary representation of the operating number. Specifically, it checked whether the input number is zero after the result of 1 reduction and the result of the decrease. If a number is a power of 2, except for the lowest level of the dual -proof, the rest are 0. The operation of minus 1 will turn the lowest level to 0, so that all bits except the lowest position will be 0. If the input number is the power of 2, the result of the calculation will be zero.
<code class="language-c++">bool IsPowerOfTwo(unsigned long long x) { return (x != 0) && ((x & (x - 1)) == 0); }</code>
For example, consider numbers 4, it is the power of 2. The binary of 4 is represented by 100. A minus 1 gets 3, and its binary is expressed as 011.100 and 011 The result of the position and operation is 000. Because the result is zero, it is confirmed that 4 is the power of 2.
This algorithm has high calculation efficiency, and provides a reliable method to check whether the given number is the power of 2 (except 0). If zero is needed, you only need to add a simple non -zero inspection, as shown in the first line of code fragment.
The above is the detailed content of Is a Number a Power of 2? A Bitwise Approach. For more information, please follow other related articles on the PHP Chinese website!