Challenge - 5 Problems
Power of Two Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this code snippet?
Given the following C# code, what will be printed to the console?
DSA C#
int n = 16; bool isPowerOfTwo = (n > 0) && ((n & (n - 1)) == 0); Console.WriteLine(isPowerOfTwo);
Attempts:
2 left
💡 Hint
Check how bitwise AND works between n and n-1 for powers of two.
✗ Incorrect
The expression (n & (n - 1)) == 0 is true only if n is a power of two. Since 16 is 2^4, the output is True.
❓ Predict Output
intermediateWhat is the output when n = 0?
Consider the same code but with n = 0. What will be printed?
DSA C#
int n = 0; bool isPowerOfTwo = (n > 0) && ((n & (n - 1)) == 0); Console.WriteLine(isPowerOfTwo);
Attempts:
2 left
💡 Hint
Remember that zero is not a power of two.
✗ Incorrect
Since n is zero, the first condition n > 0 is false, so the whole expression is false. It prints False.
🔧 Debug
advancedWhy does this code fail for negative numbers?
What is the output of this code when n = -8? Explain why.
DSA C#
int n = -8; bool isPowerOfTwo = (n > 0) && ((n & (n - 1)) == 0); Console.WriteLine(isPowerOfTwo);
Attempts:
2 left
💡 Hint
Check the first condition and how negative numbers behave with bitwise operations.
✗ Incorrect
The first condition n > 0 is false for negative numbers, so the expression is false. Negative numbers are not powers of two.
🧠 Conceptual
advancedWhich property of powers of two does the bitwise check use?
The expression
(n & (n - 1)) == 0 is used to check if n is a power of two. What property does this rely on?Attempts:
2 left
💡 Hint
Think about how binary numbers look for powers of two.
✗ Incorrect
Powers of two have exactly one bit set to 1 in their binary form. The bitwise check clears the lowest set bit, so if the result is zero, only one bit was set.
❓ Predict Output
expertWhat is the output of this recursive function for n = 32?
Analyze the following C# code and determine what it prints when n = 32.
DSA C#
bool IsPowerOfTwo(int n) { if (n == 1) return true; if (n == 0 || n % 2 != 0) return false; return IsPowerOfTwo(n / 2); } int n = 32; Console.WriteLine(IsPowerOfTwo(n));
Attempts:
2 left
💡 Hint
Trace the recursive calls dividing n by 2 each time.
✗ Incorrect
The function recursively divides n by 2. If n reaches 1, it returns true. Since 32 is a power of two, it returns True.
