Recall & Review
beginner Click to reveal answer
What does it mean for a number to be a power of two?
A number is a power of two if it can be written as 2 raised to an integer exponent, like 1, 2, 4, 8, 16, etc.
intermediate Click to reveal answer
How can you check if a number is a power of two using bitwise operations?
If a number is a power of two, it has exactly one '1' bit in its binary form. So, n & (n - 1) equals 0 for powers of two (and n > 0).
beginner Click to reveal answer
TypeScript code snippet: What does this function do?
function isPowerOfTwo(n: number): boolean {
return n > 0 && (n & (n - 1)) === 0;
}This function checks if the input number n is a power of two by verifying n is positive and that n & (n - 1) equals zero.
beginner Click to reveal answer
Why must we check that n > 0 when checking if n is a power of two?
Because zero and negative numbers are not powers of two, and the bitwise check alone would incorrectly say zero passes since 0 & (0 - 1) = 0.
beginner Click to reveal answer
What is the binary pattern of a power of two number?
It has exactly one '1' bit followed by zeros. For example, 8 in binary is 1000, which has one '1' and three '0's.
Which of these numbers is a power of two?
✗ Incorrect
16 is 2^4, so it is a power of two. The others are not powers of two.
What does the expression n & (n - 1) check for?
✗ Incorrect
n & (n - 1) equals zero only if n is a power of two.
Why do we need to check n > 0 before using n & (n - 1)?
✗ Incorrect
Zero and negative numbers are not powers of two, so we exclude them explicitly.
What is the output of isPowerOfTwo(1)?
✗ Incorrect
1 is 2^0, so it is a power of two.
Which binary number represents a power of two?
✗ Incorrect
1000 has exactly one '1' bit, so it is a power of two.
Explain how to check if a number is a power of two using bitwise operations.
Think about how powers of two look in binary and how subtracting 1 changes bits.
You got /3 concepts.
Write a simple TypeScript function to check if a number is a power of two and explain each step.
Use bitwise AND and remember to exclude zero and negatives.
You got /4 concepts.
