Input: 8
Output: true
Explanation: 8 = 2^3 → It is a power of 2
Input: 6
Output: false
Explanation: 6 is not a power of 2Approach 1: Brute Force Loop.
- If n == 0, return false
- While n % 2 == 0, divide n by 2
- If n == 1 after loop → power of 2
// C++ Example: Find Power of 2
#include <iostream>
using namespace std;
bool isPowerOfTwoLoop(int n) {
if (n <= 0) return false;
while (n % 2 == 0) {
n = n / 2;
}
return n == 1;
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (isPowerOfTwoLoop(number)) {
cout << number << " is a power of 2." << endl;
} else {
cout << number << " is not a power of 2." << endl;
}
return 0;
}
8 is a power of 2.
- Time Complexity: O(log n)
- Space Complexity: O(1)
Approach 2: Bit Manipulation Approach.
- For n = 4 (0100), n-1 = 3 (0011)
- The bitwise AND operation: 0100 & 0011 = 0000
#include <iostream>
bool isPowerOfTwo(int n) {
return (n > 0) && ((n & (n - 1)) == 0);
}
int main() {
int number = 8;
if (isPowerOfTwo(number)) {
std::cout << number << " is a power of two." << std::endl;
} else {
std::cout << number << " is not a power of two." << std::endl;
}
return 0;
}
8 is a power of two.
- Time Complexity: O(l)
- Space Complexity: O(1)