Check Power of 2 Using Bitwise
C++
Hard
3 views
Problem Description
Check if number is power of 2 using single bitwise operation.
Real Life: Powers of 2 are special in computing (2, 4, 8, 16...).
Step-by-Step Logic:
1. Power of 2 has only one set bit (100, 1000, 10000)
2. n-1 flips all bits after that single 1
3. n & (n-1) will be 0 for power of 2
4. Single operation check
Official Solution
void operator_q12_power_of_2() {
int numbers[] = {16, 18, 32, 50, 64};
for(int i = 0; i < 5; i++) {
int num = numbers[i];
if(num > 0 && (num & (num - 1)) == 0) {
cout << num << " is power of 2" << endl;
} else {
cout << num << " is NOT power of 2" << endl;
}
}
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!