Skip to content

Bit manipulation algorithm to check is_power_of_four #9452

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions bit_manipulation/decimal_to_binary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""
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()
45 changes: 45 additions & 0 deletions bit_manipulation/is_power_of_four.py
Original file line number Diff line number Diff line change
@@ -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:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: N

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: N

"""
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()