4

誰かが整数を、関連する2進数を表す整数の配列に変換する最も簡単な解決策を提供できますか..

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

他に直接またはより良い解決策はありますか?

4

3 に答える 3

8

Fixnum と Bignum には[]、n 番目のビットの値を返すメソッドがあります。これでできること

def binary n
  Math.log2(n).floor.downto(0).select {|i| n[i] == 1 }.collect {|i| 2**i}
end

2 のべき乗が大きくなりすぎるまで連続して 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

より冗長ですが、より高速です

于 2012-07-09T06:29:36.093 に答える
3

Ruby 1.8 を使用したソリューションを次に示します。( Math.log2Ruby 1.9 で追加されました):

def binary(n)
  n.to_s(2).reverse.chars.each_with_index.map {|c,i| 2 ** i if c.to_i == 1}.compact
end

実際に:

>>  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]

.reverseもちろん、値を降順で表示したい場合は、final を追加します。

于 2012-07-09T06:07:30.530 に答える
0
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

にあるこれらのソリューションcomp.lang.rubyを採用し、改良しました。

いくつかの単純なベンチマークは、このソリューションが2を底とする対数または文字列操作を含むアルゴリズムよりも高速であり、直接ビット操作よりも低速であることを示唆しています。

于 2012-07-09T10:37:54.803 に答える