循环遍历整数中的位,ruby [英] Looping through bits in an integer, ruby

查看:132
本文介绍了循环遍历整数中的位,ruby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,其中一个问题是我需要对某些整数中的位模式进行一些分析。

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

然而这不是我希望表现

我发现你可以这样做:

0.upto(num/2) do |i|
   #do something with n[i]
end

这更糟糕性能比 each_char 方法

这个循环将被执行数百万次或更多次,所以我会喜欢它尽可能快。

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


推荐答案

要确定连续1的最长序列的长度,这样更有效:

To determine the length of the longest sequence of consecutive 1's, this is more efficient:

def longest_one_chain(n)
  c = 0
  while n != 0
    n &= n >> 1
    c += 1
  end
  c
end

该方法只计算你可以按位AND数字的次数,它本身向右移1位,直到它为零。

The method simply counts how many times you can "bitwise AND" the number with itself shifted 1 bit to the right until it is zero.

示例:

                 ______ <-- longest chain
    01011011100001111110011110101010 c=0
AND  0101101110000111111001111010101
        1001100000111110001110000000 c=1, 1’s deleted
AND      100110000011111000111000000
            100000011110000110000000 c=2, 11’s deleted
AND          10000001111000011000000
                    1110000010000000 c=3, 111’s deleted
AND                  111000001000000
                     110000000000000 c=4, 1111’s deleted
AND                   11000000000000
                      10000000000000 c=5, 11111’s deleted
AND                    1000000000000
                                   0 c=6, 111111’s deleted

这篇关于循环遍历整数中的位,ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆