Complete the code to check if a number is a power of two using bitwise AND.
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & [1]) == 0;
}The expression n & (n - 1) clears the lowest set bit. If the result is zero, then n is a power of two.
Complete the code to return false immediately if the number is not positive.
public boolean isPowerOfTwo(int n) {
if ([1]) {
return false;
}
return (n & (n - 1)) == 0;
}Numbers less than or equal to zero cannot be powers of two, so we return false for those.
Fix the error in the code to correctly check if a number is a power of two.
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == [1];
}The correct check is if (n & (n - 1)) == 0, not 1. This means only one bit is set.
Fill both blanks to complete the method that returns true if n is a power of two and false otherwise.
public boolean isPowerOfTwo(int n) {
if ([1]) {
return false;
}
return (n & [2]) == 0;
}First, check if n is less than or equal to zero to return false. Then use n & (n - 1) to check if n is a power of two.
Fill all three blanks to complete the method that checks if a number is a power of two and prints the result.
public void checkPowerOfTwo(int n) {
boolean result = [1];
System.out.println("Is " + n + " a power of two? " + [2]);
if ([3]) {
System.out.println("Yes, it is.");
} else {
System.out.println("No, it is not.");
}
}Call the method isPowerOfTwo(n) to get the result. Print the result variable. Use the result variable in the if condition.
