python - 无限循环在哪里以及如何修复它?
问题描述
这是我正在上的一门课程的练习测验问题。需要修复代码。
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
解决方案
对于n = 0
,每个循环 n 为 0,将运行到下一个循环
while n % 2 == 0:
n = n / 2
推荐阅读
- jquery - 调用有效函数时Jquery验证器触发错误
- gemfire - 缓存逐出不适用于 Gemfire 分区区域
- java - 如何创建将同时服务于 Redis 缓存(NoSQL)和 Sybase ASE(关系数据库)的单个 java 域类?
- java - @RequestBody 列表永远不会为空,只是 null
- c# - 如何将子实体更改为父实体?
- javascript - 使用js调用系统参数到FullCalendar
- image-processing - 图像处理:具有 2 个阈值的高斯拉普拉斯算子
- html - 如何强制文本超出表格单元格而不改变其大小
- azure - 如何使用 PowerShell 从 Azure 表存储中获取前 X 行?
- php - PHP 从 0/0/0 00:00:00 计算日期间隔