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?
Consider the following Java method that checks if a number is a power of two. What will be printed when calling
isPowerOfTwo(16)?DSA Java
public class PowerCheck { public static boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; } public static void main(String[] args) { System.out.println(isPowerOfTwo(16)); } }
Attempts:
2 left
💡 Hint
Think about how binary AND works for powers of two.
✗ Incorrect
The method returns true if n is greater than zero and n & (n-1) equals zero. For 16 (binary 10000), 16 & 15 (01111) is 0, so it returns true.
❓ Predict Output
intermediateWhat is the output when input is zero?
What will the following Java code print when calling
isPowerOfTwo(0)?DSA Java
public class PowerCheck { public static boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; } public static void main(String[] args) { System.out.println(isPowerOfTwo(0)); } }
Attempts:
2 left
💡 Hint
Zero is not a power of two.
✗ Incorrect
Since n is 0, n > 0 is false, so the method returns false.
❓ Predict Output
advancedWhat is the output of this code with negative input?
What will be printed when calling
isPowerOfTwo(-8) with the following code?DSA Java
public class PowerCheck { public static boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; } public static void main(String[] args) { System.out.println(isPowerOfTwo(-8)); } }
Attempts:
2 left
💡 Hint
Negative numbers are not powers of two in this context.
✗ Incorrect
The method checks if n is greater than zero. Since -8 is less than zero, it returns false.
🔧 Debug
advancedWhat will this code print?
What will this Java code print when compiled and run?
DSA Java
public class PowerCheck { public static boolean isPowerOfTwo(int n) { return n > 0 & (n & (n - 1)) == 0; } public static void main(String[] args) { System.out.println(isPowerOfTwo(4)); } }
Attempts:
2 left
💡 Hint
Check the difference between & and && operators in Java.
✗ Incorrect
The code compiles and prints true. Operator precedence parses it as (n > 0) & ((n & (n - 1)) == 0). Relational > has higher precedence than ==, which is higher than bitwise &. For n=4, both sides evaluate to true, and boolean & boolean is true (non-short-circuit logical AND).
🧠 Conceptual
expertWhy does the expression (n & (n - 1)) == 0 check for power of two?
Choose the best explanation for why the expression
(n & (n - 1)) == 0 is used to check if n is a power of two.Attempts:
2 left
💡 Hint
Think about binary representation of powers of two and what happens when you subtract 1.
✗ Incorrect
A power of two in binary has exactly one bit set to 1. Subtracting 1 flips that bit and all bits after it. ANDing n and n-1 clears the lowest set bit. If the result is zero, n had only one set bit, so it is a power of two.
