有人可以帮我解决这个问题吗?

时间:2020-05-11 03:07:40

标签: python-3.x

以下代码可能导致无限循环。修改代码,使其对所有数字均能成功完成。

注意:尝试以数字0作为输入运行函数,然后看看会得到什么!

   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

3 个答案:

答案 0 :(得分:1)

def is_power_of_two(n):
    if n == 0:  # Check special case
        return False
    else:
        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
        else:
            return False

答案 1 :(得分:1)

0%2 ==是真的,当n = 0时n = n / 2,我的解决方法是:

NaN

答案 2 :(得分:0)

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 # Except 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 # edit indent


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