0
0
DSA Pythonprogramming~10 mins

Check if Number is Power of Two in DSA Python - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if a number is a power of two using bitwise AND.

DSA Python
def is_power_of_two(n):
    return n > 0 and (n & ([1])) == 0
Drag options to blanks, or click blank then click option'
An - 1
Bn + 1
C1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 instead of n - 1
Checking n & 1 which only checks if n is odd
Using 0 instead of n - 1 in the bitwise AND
2fill in blank
medium

Complete the code to return False immediately if the number is not positive.

DSA Python
def is_power_of_two(n):
    if [1]:
        return False
    return (n & (n - 1)) == 0
Drag options to blanks, or click blank then click option'
An == 0
Bn <= 0
Cn < 0
Dn >= 0
Attempts:
3 left
💡 Hint
Common Mistakes
Checking only for n == 0 and missing negative numbers
Using n >= 0 which includes zero and positive numbers
3fill in blank
hard

Fix the error in the code to correctly check if n is a power of two.

DSA Python
def is_power_of_two(n):
    if n <= 0:
        return False
    return (n & ([1])) == 0
Drag options to blanks, or click blank then click option'
An - 1
Bn + 1
C1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 instead of n - 1
Using 1 or 0 directly in the bitwise AND
4fill in blank
hard

Fill both blanks to complete the function that returns True if n is a power of two, else False.

DSA Python
def is_power_of_two(n):
    if n [1] 0:
        return False
    return (n & (n [2] 1)) == 0
Drag options to blanks, or click blank then click option'
A<=
B>
C-
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using > 0 instead of <= 0 in the if condition
Using + 1 instead of - 1 in the bitwise AND
5fill in blank
hard

Fill all three blanks to complete the function that checks if a number is a power of two.

DSA Python
def is_power_of_two(n):
    if n [1] 0:
        return False
    return (n [2] (n [3] 1)) == 0
Drag options to blanks, or click blank then click option'
A<=
B&
C-
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using + instead of - in the expression
Using | instead of & for bitwise operation
Checking n < 0 instead of n <= 0