From c08e1388e664e9f392d0a03835879c0efd49a403 Mon Sep 17 00:00:00 2001 From: siddwarr Date: Mon, 2 Oct 2023 21:28:17 +0530 Subject: [PATCH] added power_of_4 --- bit_manipulation/power_of_4 | 61 +++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 bit_manipulation/power_of_4 diff --git a/bit_manipulation/power_of_4 b/bit_manipulation/power_of_4 new file mode 100644 index 000000000..071a53a5d --- /dev/null +++ b/bit_manipulation/power_of_4 @@ -0,0 +1,61 @@ +""" + +Task: +Given a positive int number. Return True if this number is power of 4 +or False otherwise. + +Implementation notes: Use bit manipulation. +For example if the number is the power of 2 it's bits representation: +n = 0..100..00 +n - 1 = 0..011..11 + +n & (n - 1) - no intersections = 0 +If the number is a power of 4 then it should be a power of 2 and the set bit should be at an odd position +""" + + +def power_of_4(number: int) -> bool: + """ + Return True if this number is power of 4 or False otherwise. + + >>> power_of_4(0) + False + >>> power_of_4(1) + True + >>> power_of_4(2) + False + >>> power_of_4(4) + True + >>> power_of_4(6) + False + >>> power_of_4(8) + False + >>> power_of_4(17) + False + >>> power_of_4(-1) + Traceback (most recent call last): + ... + ValueError: number must be positive + >>> power_of_4(1.2) + Traceback (most recent call last): + ... + TypeError: unsupported operand type(s) for &: 'float' and 'float' + + """ + if number <= 0: + raise ValueError("number must be positive") + if number & (number - 1) == 0: + c = 0 + while number: + c+=1 + number>>=1 + if c&1==0: + return True + else: + return False + + +if __name__ == "__main__": + import doctest + + doctest.testmod()