1. Repeated Division by 2
Intuition
If n <= 0, return false. While n % 2 == 0, divide n /= 2. If n == 1, return true; else return false.
When to apply: Basic mathematical definition.
Algorithm
- Step 1: If n <= 0, return false.
- Step 2: While n % 2 == 0, n /= 2.
- Step 3: Return n == 1.
#include <iostream> using namespace std; bool isPowerOfTwoBrute(int n) { if (n <= 0) return false; while (n % 2 == 0) { n /= 2; } return n == 1;} int main() { cout << boolalpha; cout << "Brute (1): " << isPowerOfTwoBrute(1) << endl; // true cout << "Brute (16): " << isPowerOfTwoBrute(16) << endl; // true cout << "Brute (3): " << isPowerOfTwoBrute(3) << endl; // false return 0;}Time & Space Complexity
- Time complexity:
O(log n) - Space complexity:
O(1)