Skip to content

Instantly share code, notes, and snippets.

@juandesant
Created February 22, 2021 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juandesant/a4dbedce3986dbf684728ff8b2c2f605 to your computer and use it in GitHub Desktop.
Save juandesant/a4dbedce3986dbf684728ff8b2c2f605 to your computer and use it in GitHub Desktop.
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