CodeEval
(設問の意味があってるかわからんけど)
3つの数字、aとp1,p2が与えられた時
aのp1ビットとp2ビットが同じあればtrue、異なればfalseを出力。
(と解釈)
inputはこんな感じ。
86,2,3 125,1,2
結果。
true false
設問
Given a number n and two integers p1,p2 determine if the bits in position p1 and p2 are the same or not. Positions p1,p2 and 1 based.
Input sample:
The first argument will be a text file containing a comma separated list of 3 integers, one list per line. e.g.
86,2,3 125,1,2
Output sample:
Print to stdout, 'true'(lowercase) if the bits are the same, else 'false'(lowercase).
e.g.
true false
やってみた
#!/usr/bin/env ruby ARGF.lines do |line| a,p1,p2 = line.split(',').map(&:to_i) puts ((a >> (p1-1)) & 1) == ((a >> (p2-1)) & 1) end
追記
これすごい。Integer.to_s(2)なんてできたんだ。
RubyでBit Positionsを解く -CodeEval - hp12c
def same_digit_on?(n, pos1, pos2) bits = n.to_s(2) bits[-pos1] == bits[-pos2] end
2012/01/30追記
masassiezさんthanks。
コメントいただいたように、Fixnum[nth]ってのでもビットを返せる。
面白い。
def same_digit_on?(n, pos1, pos2) n[pos1-1] == n[pos2-1] end