How to write 4 different functions that check if a number is a power of 2 in Python

1 Answer

0 votes
import math

# Method A: Bit-counting
def is_power_of_two_a(x):
    if x <= 0:
        return False
    return bin(x).count("1") == 1

# Method B: Bitwise trick
def is_power_of_two_b(x):
    return x > 0 and (x & (x - 1)) == 0

# Method C: Repeated division
def is_power_of_two_c(x):
    if x <= 0:
        return False
    while x % 2 == 0:
        x //= 2
    return x == 1

# Method D: Using logarithms
def is_power_of_two_d(x):
    if x <= 0:
        return False
    logv = math.log(x, 2)
    return abs(logv - round(logv)) < 1e-10


if __name__ == "__main__":
    test1 = 16   # true
    test2 = 18   # false

    print("A:", is_power_of_two_a(test1), ",", is_power_of_two_a(test2))
    print("B:", is_power_of_two_b(test1), ",", is_power_of_two_b(test2))
    print("C:", is_power_of_two_c(test1), ",", is_power_of_two_c(test2))
    print("D:", is_power_of_two_d(test1), ",", is_power_of_two_d(test2))



"""
OUTPUT:

A: True , False
B: True , False
C: True , False
D: True , False

"""

 



answered Apr 2 by avibootz

Related questions

...