如何找到最长连续位串的长度(1或0)?
00000000 11110000 00000000 00000000 - >如果为0,则长度为20
11111111 11110000 11110111 11111111 - >如果为1则长度为12
我正在制作一个程序,其中一个问题是我需要对某些整数中的位模式进行一些分析.
因此,我希望能够做到这样的事情:
#Does **NOT** work:
num.each_bit do |i|
#do something with i
end
Run Code Online (Sandbox Code Playgroud)
通过这样做,我能够创造出有效的东西:
num.to_s(2).each_char do |c|
#do something with c as a char
end
Run Code Online (Sandbox Code Playgroud)
然而,这没有我想要的性能.
我发现你可以这样做:
0.upto(num/2) do |i|
#do something with n[i]
end
Run Code Online (Sandbox Code Playgroud)
这比该each_char方法的性能更差
这个循环将被执行数百万次或更多次,所以我希望它尽可能快.
作为参考,这是整个功能
@@aHashMap = Hash.new(-1)
#The method finds the length of the longes continuous chain of ones, minus one
#(101110 = 2, 11 = 1, 101010101 = 0, 10111110 = 4)
def afunc(n)
if @@aHashMap[n] != -1
return @@aHashMap[n]
end …Run Code Online (Sandbox Code Playgroud)