Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Power of Two in C
In C programming, checking whether a number is a power of two is a common problem that can be solved efficiently using bitwise operations. A power of two is any number that can be expressed as 2n where n is a non-negative integer (1, 2, 4, 8, 16, 32, etc.).
Syntax
bool isPowerOfTwo(int n); // Returns true if n is a power of 2, false otherwise
Algorithm
The key insight is that powers of two have a specific binary pattern − they have exactly one bit set to 1 (the MSB) and all other bits are 0. For example:
- 16 = 10000 (binary)
- 15 = 01111 (binary)
- 16 & 15 = 10000 & 01111 = 00000 = 0
The expression n & (n-1) will return 0 if and only if n is a power of 2.
Example
Here's a complete implementation to check if numbers are powers of two −
#include <stdio.h>
#include <stdbool.h>
bool isPowerOfTwo(int n) {
return (n > 0 && !(n & (n - 1)));
}
int main() {
printf("%s
", isPowerOfTwo(16) ? "true" : "false");
printf("%s
", isPowerOfTwo(12) ? "true" : "false");
printf("%s
", isPowerOfTwo(1) ? "true" : "false");
printf("%s
", isPowerOfTwo(32) ? "true" : "false");
return 0;
}
true false true true
How It Works
The function works by checking two conditions:
- n > 0: Ensures the number is positive (powers of 2 are always positive)
- !(n & (n-1)): Uses bitwise AND to check if exactly one bit is set
Key Points
- Time complexity: O(1) - constant time operation
- Space complexity: O(1) - no extra space required
- The number 1 is considered a power of 2 (20 = 1)
- Negative numbers and zero are not powers of 2
Conclusion
Using bitwise operations with n & (n-1) provides an elegant and efficient solution to check if a number is a power of two. This approach leverages the unique binary pattern of powers of two for optimal performance.
