Created
February 22, 2021 12:58
-
-
Save juandesant/a4dbedce3986dbf684728ff8b2c2f605 to your computer and use it in GitHub Desktop.
Python reply to https://extras.waynewbishop.com/challenge/power-of-two
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def is_power_of_two(an_int): | |
# We use the binary representation to work with | |
bits = bin(an_int)[2:] # truncates the "0b" part of the string | |
# A power of two only has one bit set, so the sum of all bits needs to be 1 | |
return sum([int(x) for x in list(bits)]) == 1 | |
def is_power_of_two_recursive(an_int): | |
if an_int < 0: | |
return is_power_of_two_recursive(-an_int) | |
elif an_int == 0: | |
return False | |
elif an_int == 1: | |
return True | |
else: | |
# recursive, with early bailout if there is a non-divisible by two part | |
return an_int % 2 == 0 and is_power_of_two_recursive(an_int//2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment