【发布时间】:2022-12-01 22:21:52
【问题描述】:
def is_power_of_two(n):
# Check if the number can be divided by two without a remainder
while n % 2 == 0:
n = n / 2
# If after dividing by two the number is 1, it's a power of two
if n == 1:
return True
if n != 0:
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
This is a excercice from Coursera's Python course. I don't know why it don't finish when n=0.
【问题讨论】:
-
When you pass
n = 0thenn = n / 2will continue to re-assign0ton, and therefore the condition for yourwhileloop is alwaysTrue -
Writing solution @Tomerikoo
-
Why I was down voted
标签: python