我遇到了编码挑战:检查给定的正数组是否为幂2,1否则返回0.前
A=[2,3,4]输出: A=[1,0,1]
输入: A =[1048,2048,1048576]
A=[1,1,1]我想出了这个功能.
def checkPw (arr)
arr.map{|a| a != 0 && (a%2==0)?1 :0 }
end
Run Code Online (Sandbox Code Playgroud)
这个函数通过了提供的测试,但我不确定它是否是干净的方法.我想知道是否有更明确的方法来检查数组元素的功能.
有检查是否正整数是,这是比较若的位与2的幂的伎俩x和x - 1为零.因此,您可以对数组执行以下操作a以检查每个元素是否为2的幂:
a.all?{|x| x & (x - 1) == 0}
Run Code Online (Sandbox Code Playgroud)
例子:
[2048, 2048, 1048576].all?{|x| x & (x - 1) == 0}
=> true
[1048, 2048, 1048576].all?{|x| x & (x - 1) == 0}
=> false
Run Code Online (Sandbox Code Playgroud)
如果要对每个元素进行检查:
a.map{|x| x & (x - 1) == 0 ? 1 : 0}
Run Code Online (Sandbox Code Playgroud)
其它的办法:
def po2?(arr)
arr.map { |n| (n.to_s(2) =~ /^10*$/) ? 1 : 0 }
end
po2? [1,2,4,7,1024,1025]
#=> [1,1,1,0,1,0]
Run Code Online (Sandbox Code Playgroud)
例如,
n = 1024
s = n.to_s(2)
#=> "10000000000"
s =~ /^10*$/)
#=> true
n = 1025
s = n.to_s(2)
#=> "10000000001"
s =~ /^10*$/)
#=> false
Run Code Online (Sandbox Code Playgroud)