0
0
DSA Pythonprogramming~5 mins

Check if Number is Power of Two in DSA Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A18
B32
C16
D64
What does the expression n & (n - 1) do when n is a power of two?
AReturns n
BReturns 0
CReturns n-1
DReturns 1
Why do we check if n > 0 before using the bit trick?
ABecause negative numbers are powers of two
BBecause it speeds up the calculation
CBecause zero and negatives are not powers of two
DBecause it changes the bit pattern
Which binary pattern represents a power of two?
ANo bits set
BMultiple bits set to 1
CAll bits set to 1
DExactly one bit set to 1
What will is_power_of_two(0) return using the bit trick method?
AFalse
BTrue
CError
DNone
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.