6

このC式をJで書くにはどうすればよいですか?(ここで、xは入力整数で、aは一時変数です)

((a= ~x & (~x >> 1)) ^= a ? 0 : (a ^ (a & (a - 1))) | (a ^ (a & (a - 1))) << 1);

編集:

より読みやすい形式で:

    int a = (~x) & ((~x) >> 1);
    if (a == 0) return 0;
    int b = a ^ (a & (a - 1));
    return b | (b << 1);
4

2 に答える 2

5

テストを行わない場合、基本的な書き起こしは次のようになります。

Shift =: (33 b.)
And   =: (17 b.)
Not   =: (26 b.)
Xor   =: (22 b.)
Or    =: (23 b.)

BastardFunction =: 3 : 0
  a =. (Not y) And (_1 Shift (Not y))
  if. a do.
    b =. a  Xor (a And a - 1)
    (1 Shift b) Or b
  else.
    0
  end.
)

しかし、もっと賢いアプローチがあるかもしれません。

于 2010-09-30T00:38:52.903 に答える
3

これは小さな分析です(「読み取り可能な形式」バージョンの):

usnigned int nx = ~x;   // I suppose it's unsigned 
int a = nx & (nx >> 1); 
// a will be 0 if there are no 2 consecutive "1" bits.
// or it will contain "1" in position N1 if nx had "1" in positions N1 and N1 + 1
if (a == 0) return 0;   // we don't have set bits for the following algorithm
int b = a ^ (a & (a - 1));  
// a - 1 : will reset the least 1 bit and will set all zero bits (say, NZ) that were on smaller positions
// a & (a - 1) : will leave zeroes in all (NZ + 1) LSB bits (because they're only bits that has changed
// a ^ (a & (a - 1)) : will cancel the high part, leaving only the smallest bit that was set in a
// so, for a = 0b0100100 we'll obtain a power of two: b = 0000100
return b | (b << 1);    
// knowing that b is a power of 2, the result is b + b*2 => b*3

アルゴリズムは、変数の最初の 2 ビット (LSB から開始) の連続0するビットを探しているようです。x何もない場合、結果は 0 です。たとえば、 position で見つかった場合、結果にはとPZの 2 つのセット ビットが含まれます。PZPZ+1

于 2010-09-30T00:25:27.653 に答える