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 function to check if a number is a power of two, what will be printed when calling
isPowerOfTwo(16)?DSA Typescript
function isPowerOfTwo(n: number): boolean {
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 uses a bitwise trick: a power of two number has exactly one bit set. The expression n & (n - 1) clears the lowest set bit. If the result is zero, it means only one bit was set, so the number is a power of two.
❓ Predict Output
intermediateWhat is the output of this code snippet?
What will
isPowerOfTwo(0) return in the following function?DSA Typescript
function isPowerOfTwo(n: number): boolean {
return n > 0 && (n & (n - 1)) === 0;
}
console.log(isPowerOfTwo(0));Attempts:
2 left
💡 Hint
Zero is not a power of two.
✗ Incorrect
The function returns false because the first condition n > 0 fails for zero.
🔧 Debug
advancedWhat error does this code raise?
Identify the error when running this code snippet:
DSA Typescript
function isPowerOfTwo(n: number): boolean {
return n > 0 && (n & (n - 1)) === 0;
}
console.log(isPowerOfTwo(8));Attempts:
2 left
💡 Hint
Check the operator used for comparison.
✗ Incorrect
The code uses a single equals sign = instead of the comparison operator ===, causing a syntax error.
🚀 Application
advancedHow many numbers between 1 and 16 (inclusive) are powers of two?
Using the power of two check, count how many numbers from 1 to 16 are powers of two.
DSA Typescript
function isPowerOfTwo(n: number): boolean {
return n > 0 && (n & (n - 1)) === 0;
}
let count = 0;
for (let i = 1; i <= 16; i++) {
if (isPowerOfTwo(i)) count++;
}
console.log(count);Attempts:
2 left
💡 Hint
Powers of two up to 16 are 1, 2, 4, 8, 16.
✗ Incorrect
The powers of two between 1 and 16 are 1, 2, 4, 8, and 16, totaling 5 numbers.
🧠 Conceptual
expertWhich option correctly explains why
n & (n - 1) === 0 checks for power of two?Why does the expression
n & (n - 1) === 0 return true only for powers of two?Attempts:
2 left
💡 Hint
Think about binary representation of powers of two.
✗ Incorrect
Powers of two have only one bit set. Subtracting 1 flips all bits after that set bit. ANDing them clears the only set bit, resulting in zero.
