【发布时间】:2015-10-12 23:32:26
【问题描述】:
如果 num 是 2 的幂,我有此代码返回 true。
def is_power_of_two?(num)
result = num.inject(0) {|n1, n2| n2 ** n1}
if result == num
true
else
false
end
end
p is_power_of_two?(16)
但我不断收到错误消息。我该如何修复和简化这段代码?
【问题讨论】:
-
为什么不用log2函数呢?如果输入在 ^2 上,应该返回整数。谷歌
log2 1024 -
不是 Ruby 专家,但您似乎在整数而不是数组上使用注入方法
-
我尝试使用
num.to_a将 num 转换为数组,但这对我不起作用 -
Log2 看起来是个好主意,但我怎样才能合并它以确保我只得到整数?