首页 > 解决方案 > 无限循环在哪里以及如何修复它?

问题描述

这是我正在上的一门课程的练习测验问题。需要修复代码。

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
  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

标签: pythonwhile-loopinfinite-loop

解决方案


对于n = 0,每个循环 n 为 0,将运行到下一个循环

  while n % 2 == 0:
    n = n / 2

推荐阅读