Recall & Review
beginner
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.
Click to reveal answer
beginner
Which bit pattern property helps to check if a number is a power of two?
A power of two has exactly one bit set to 1 in its binary form, and all other bits are 0.
Click to reveal answer
intermediate
Explain the expression: n & (n - 1) == 0 for checking power of two.
If n is a power of two, n & (n - 1) clears the only set bit, resulting in 0. For other numbers, it won't be zero.
Click to reveal answer
beginner
Why must we check that n > 0 when checking if n is a power of two?
Because zero or negative numbers are not powers of two, and the bit trick only works for positive integers.
Click to reveal answer
beginner
Write a simple Python function to check if a number is a power of two using bit manipulation.
def is_power_of_two(n):
return n > 0 and (n & (n - 1)) == 0
Click to reveal answer
Which of these numbers is NOT a power of two?
✗ Incorrect
18 is not a power of two because it cannot be expressed as 2 raised to an integer.
What does the expression n & (n - 1) do when n is a power of two?
✗ Incorrect
For powers of two, n & (n - 1) clears the only set bit, resulting in 0.
Why do we check if n > 0 before using the bit trick?
✗ Incorrect
Zero and negative numbers are not powers of two, so we exclude them first.
Which binary pattern represents a power of two?
✗ Incorrect
A power of two has exactly one bit set to 1 in binary.
What will is_power_of_two(0) return using the bit trick method?
✗ Incorrect
0 is not a power of two, so the function returns False.
Describe how to check if a number is a power of two using bit manipulation.
Think about how binary bits change when subtracting 1.
You got /3 concepts.
Write a Python function to check if a number is a power of two and explain each step.
Use the bit trick and explain why it works.
You got /4 concepts.