Skip to content

Instantly share code, notes, and snippets.

@nagarjunareddyg
Forked from Kimjunkuk/answer.py
Created January 5, 2023 10:54
Show Gist options
  • Select an option

  • Save nagarjunareddyg/1f672f14c68d106c4876ecdb31ac8120 to your computer and use it in GitHub Desktop.

Select an option

Save nagarjunareddyg/1f672f14c68d106c4876ecdb31ac8120 to your computer and use it in GitHub Desktop.
3. Question 3 The following code can lead to an infinite loop. Fix the code so that it can finish successfully for all numbers. Note: Try running your function with the number 0 as the input, and see what you get!
def is_power_of_two(n):
# Check if the number can be divided by two without a remainder
while n % 2 == 0:
if n<=0:
return False
else:
n = n / 2
return True
break
# If after dividing by two the number is 1, it's a power of two
if n == 1:
return True
return False
print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
print(is_power_of_two(9)) # Should be False
# DO NOT DELETE THIS COMMENT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment