diff --git a/bit_manipulation/decimal_to_binary.py b/bit_manipulation/decimal_to_binary.py new file mode 100644 index 000000000000..46a6243224f6 --- /dev/null +++ b/bit_manipulation/decimal_to_binary.py @@ -0,0 +1,46 @@ +""" +Author :- mehul-sweeti-agrawal + +Task :- Given a positive decimal integer, convert it to binary + + Input - 9 + Output - 1001 + +""" + + +def convert_to_binary(number: int) -> int: + """ + Returns binary equivalent of a decimal number + >>> convert_to_binary(8) + 1000 + >>> convert_to_binary(5) + 101 + >>> convert_to_binary(-3) + Traceback (most recent call last): + ... + ValueError: number must be non-negative + >>> convert_to_binary(9.8) + Traceback (most recent call last): + ... + TypeError: unsupported operand type(s) for &: 'float' and 'int' + """ + + # For negative numbers + if number < 0: + raise ValueError("number must be non-negative") + + power = 1 # helper variable + ans = 0 # stores binary equivalent of decimal number + while number: + if number & 1: + ans += power + power *= 10 + number >>= 1 + return ans + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/bit_manipulation/is_power_of_four.py b/bit_manipulation/is_power_of_four.py new file mode 100644 index 000000000000..b46eb612fc84 --- /dev/null +++ b/bit_manipulation/is_power_of_four.py @@ -0,0 +1,45 @@ +""" +Author :- mehul-sweeti-agrawal + +Task :- Given an integer N, find whether that integer is a power of 4 or not. + + Input - N + Output - Yes/No + +""" + + +def is_power_of_four(N: int) -> bool: + """ + Returns whether a number is a power of 4 or not + >>> is_power_of_four(8) + False + >>> is_power_of_four(4) + True + >>> is_power_of_four(16) + True + >>> is_power_of_four(-1) + Traceback (most recent call last): + ... + ValueError: number must be positive + >>> is_power_of_four(9.8) + Traceback (most recent call last): + ... + TypeError: unsupported operand type(s) for &: 'float' and 'float' + """ + + # For non-positive numbers + if N <= 0: + raise ValueError("number must be positive") + + # If number is a power of 2 and ends with 4 or 6 + if (N & (N - 1) == 0) and (N % 10 == 6 or N % 10 == 4): + return True + else: + return False + + +if __name__ == "__main__": + import doctest + + doctest.testmod()