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 JavaScript code snippet?
DSA Javascript
function isPowerOfTwo(n) {
return n > 0 && (n & (n - 1)) === 0;
}
console.log(isPowerOfTwo(16));Attempts:
2 left
💡 Hint
Remember that powers of two have only one bit set in binary.
✗ Incorrect
The function returns true if n is greater than zero and n & (n-1) equals zero, which is true only for powers of two.
❓ Predict Output
intermediateOutput of power of two check with loop
What will be printed by this code?
DSA Javascript
function isPowerOfTwo(n) {
if (n < 1) return false;
while (n % 2 === 0) {
n = n / 2;
}
return n === 1;
}
console.log(isPowerOfTwo(18));Attempts:
2 left
💡 Hint
Check if the number can be divided by 2 repeatedly until it becomes 1.
✗ Incorrect
18 is not a power of two because dividing by 2 repeatedly does not end at 1.
🔧 Debug
advancedIdentify the error in power of two check
What error will this code produce when run?
DSA Javascript
function isPowerOfTwo(n) {
return n && (n & (n - 1)) === 0;
}
console.log(isPowerOfTwo(8));Attempts:
2 left
💡 Hint
Check operator precedence and how the expression is evaluated.
✗ Incorrect
The expression is parsed as n && ((n & (n - 1)) === 0) because === has higher precedence than &&. For n=8, (8 & 7) = 0, 0 === 0 is true, then 8 && true is true. The code correctly returns and prints true.
❓ Predict Output
advancedOutput of recursive power of two check
What is the output of this recursive function call?
DSA Javascript
function isPowerOfTwo(n) {
if (n === 1) return true;
if (n < 1 || n % 2 !== 0) return false;
return isPowerOfTwo(n / 2);
}
console.log(isPowerOfTwo(32));Attempts:
2 left
💡 Hint
Think about the base case and how the function reduces the problem size.
✗ Incorrect
The function correctly checks if n is a power of two by recursively dividing by 2 until it reaches 1.
🧠 Conceptual
expertWhy does n & (n - 1) === 0 check power of two?
Which explanation best describes why the expression 'n & (n - 1) === 0' checks if n is a power of two?
Attempts:
2 left
💡 Hint
Think about binary representation of powers of two and what subtracting 1 does.
✗ Incorrect
Powers of two have exactly one bit set. Subtracting 1 flips that bit and all bits after it, so ANDing with n clears that bit and results in zero only for powers of two.
