0

次の Java コードがあります。

long a = Long.parseLong("11001100", 2);
long b = Long.parseLong("11000000", 2);
int npos = 0 ;
int pos = 0 ;
long n = ~(a ^ b) ;
int cnt = 0;
while (n != 0) {
  pos++ ;
  if ((n & 3) == 3) cnt++; // count how many matches
  else{
    npos = pos ;  // position that not matched also giving wrong which should be 2 nd position.
  }
  n >>>= 2;
}

System.out.println(npos + "  " + cnt) ; // also print which two bits are not matched i.e. 00 and 11

2 つの整数で一致する 2 ビット シーケンスの数を見つけようとしています。また、一致しない 2 つのビットを見つけたいと思います。誰でもそれを行う方法を手伝ってもらえますか?

PS: 元のコードには文字列がなく、整数しかありません。したがって、文字列操作はできません。

編集:

long a = Long.parseLong("11000100", 2);
long b = Long.parseLong("11000000", 2);
long mask = 0x03;
int npos = 0 ;
int cnt = 0;
long p1 = 0;
long p2 = 0;
for (int pos = 0; pos < 64; pos++, mask <<= 2) {

  if ((a & mask) == (b & mask)) {
     cnt++; // count how many matches
  } else {
    npos = pos ;  // *last* position that did not match
    p1 = (a & mask) ; // two bits that not matched
    p2 = (b & mask) ; // two bits that not matched
  }
}

  System.out.println(npos + "  " + cnt + " " + p1 + " " + p2) ; // also print which two bits are not matched i.e. 00 and 01
4

1 に答える 1

3

基数パラメーターを持つメソッドを使用して、整数を 10 進数として解析します。おそらくバイナリ整数として解析する必要があります。

long a = Long.parseInt("11001100", 2);
long b = Long.parseInt("11000000", 2);

マスクを使用して 2 つの値を比較するループを実行する方が簡単な場合があります。

long mask = 0x03;
int npos = 0 ;
int cnt = 0;

for (int pos = 0; pos < 32; pos++, mask <<= 2) {

  if ((a & mask) == (b & mask)) {
     cnt++; // count how many matches
  } else {
    npos = pos ;  // *last* position that did not match
  }
}
于 2012-08-07T19:00:49.370 に答える