[英]How to convert an integer into a Binary Array..
Can someone give the simplest solution to convert an integer into a Array of Integer representing its relevant binary digits.. 有人可以提供最简单的解决方案将整数转换为表示其相关二进制数字的整数数组。
Input => Output
1 => [1]
2 => [2]
3 => [2,1]
4 => [4]
5 => [4,1]
6 => [4,2]
One way is :
Step 1 : 9.to_s(2) #=> "1001"
Step 2 : loop with the count of digit
use / and %
based on loop index, multiply with 2
store in a array
Is there any other direct or better solution? 还有其他直接或更好的解决方案吗?
Fixnum and Bignum have a []
method, that returns the value of the nth bit. Fixnum和Bignum有一个
[]
方法,它返回第n位的值。 With this we can do 有了这个我们就能做到
def binary n
Math.log2(n).floor.downto(0).select {|i| n[i] == 1 }.collect {|i| 2**i}
end
You could avoid the call to Math.log2 by calculating successive powers of 2 until that power was too big: 您可以通过计算2的连续幂来避免对Math.log2的调用,直到该功率太大为止:
def binary n
bit = 0
two_to_the_bit = 1
result = []
while two_to_the_bit <= n
if n[bit] == 1
result.unshift two_to_the_bit
end
two_to_the_bit = two_to_the_bit << 1
bit += 1
end
result
end
more verbose, but faster 更冗长,但速度更快
Here is a solution that uses Ruby 1.8. 这是一个使用Ruby 1.8的解决方案。 (
Math.log2
was added in Ruby 1.9): (在Ruby 1.9中添加了
Math.log2
):
def binary(n)
n.to_s(2).reverse.chars.each_with_index.map {|c,i| 2 ** i if c.to_i == 1}.compact
end
In action: 在行动:
>> def binary(n)
>> n.to_s(2).reverse.chars.each_with_index.map {|c,i| 2 ** i if c.to_i == 1}.compact
>> end
=> nil
>> binary(19)
=> [1, 2, 16]
>> binary(24)
=> [8, 16]
>> binary(257)
=> [1, 256]
>> binary(1000)
=> [8, 32, 64, 128, 256, 512]
>> binary(1)
=> [1]
Add a final .reverse
if you would like to see the values in descending order, of course. 如果您希望以降序查看值,请添加最终的
.reverse
。
class Integer
def to_bit_array
Array.new(size) { |index| self[index] }.reverse!
end
def bits
to_bit_array.drop_while &:zero?
end
def significant_binary_digits
bits = self.bits
bits.each_with_object(bits.count).with_index.map do |(bit, count), index|
bit * 2 ** (count - index - 1)
end.delete_if &:zero?
end
end
Adapted from and improved upon these solutions found in comp.lang.ruby
. 改编自
comp.lang.ruby
这些解决方案并对其进行改进。
Some simple benchmarks suggest that this solution is faster than algorithms involving either base-2 logarithms or string manipulation and slower than direct bit manipulation . 一些简单的基准测试表明, 这种解决方案比涉及base-2对数或字符串操作的算法更快,而且比直接位操作慢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.