Challenge - 5 Problems
Power of Two Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of power of two check using bitwise AND
What is the output of the following C++ code snippet?
DSA C++
int n = 16; bool isPowerOfTwo = (n & (n - 1)) == 0 && n != 0; std::cout << (isPowerOfTwo ? "Yes" : "No") << std::endl;
Attempts:
2 left
💡 Hint
Remember that powers of two have only one bit set in binary.
✗ Incorrect
The expression n & (n - 1) clears the lowest set bit. For powers of two, this results in zero. Since 16 is a power of two, the output is "Yes".
❓ Predict Output
intermediateOutput when input is zero
What does the following code print when n = 0?
DSA C++
int n = 0; bool isPowerOfTwo = (n & (n - 1)) == 0 && n != 0; std::cout << (isPowerOfTwo ? "Yes" : "No") << std::endl;
Attempts:
2 left
💡 Hint
Zero is not a power of two.
✗ Incorrect
The condition n != 0 ensures zero is excluded. So the output is "No".
🔧 Debug
advancedIdentify the error in power of two check
What error does this code produce?
DSA C++
int n = 8; bool isPowerOfTwo = (n & n - 1) == 0; std::cout << (isPowerOfTwo ? "Yes" : "No") << std::endl;
Attempts:
2 left
💡 Hint
Check operator precedence in the expression.
✗ Incorrect
The expression (n & n - 1) is parsed as (n & n) - 1 due to operator precedence, which is incorrect. This causes wrong output.
🧠 Conceptual
advancedWhy does (n & (n-1)) == 0 check power of two?
Which explanation correctly describes why
(n & (n-1)) == 0 checks if n is a power of two?Attempts:
2 left
💡 Hint
Think about what happens to the binary bits when subtracting 1.
✗ Incorrect
Subtracting 1 flips the lowest set bit and all bits after it. ANDing with n clears that bit. If the result is zero, n had only one set bit, meaning it is a power of two.
🚀 Application
expertCount how many numbers are powers of two in a list
Given the list
{3, 4, 6, 8, 16, 18}, how many numbers are powers of two?Attempts:
2 left
💡 Hint
Check each number with the bitwise power of two test.
✗ Incorrect
4, 8, and 16 are powers of two. So the count is 3.
