I am making a program where one of the problems is that I need to do some analysis of the bit pattern in some integers.
Because of this I would like to be able to do something like this:
#Does **NOT** work:
num.each_bit do |i|
#do something with i
end
I was able to make something that works, by doing:
num.to_s(2).each_char do |c|
#do something with c as a char
end
This however does not have the performance I would like.
I have found that you can do this:
0.upto(num/2) do |i|
#do something with n[i]
end
This have even worse performance than the each_char
method
This loop is going to be executed millions of times, or more, so I would like it to be as fast as possible.
For reference, here is the entirety of the function
@@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
num = 0
tempnum = 0
prev = false
(n.to_s(2)).each_char do |i|
if i
if prev
tempnum += 1
if tempnum > num
num = tempnum
end
else
prev = true
end
else
prev = false
tempnum = 0
end
end
@@aHashMap[n] = num
return num
end
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…