1

我有一个很长的号码。现在我想要的是(以伪代码给出),

for each two bits of that long

if the two bits == 11

then count++

(for example if number is "11 01 10 00 11" it will give count = 2)

任何人都可以帮助我如何在 Java 中有效地做到这一点吗?

4

1 回答 1

2
public static int count11(long n) {
  int cnt = 0;
  while (n != 0) {
    if ((n & 3) == 3) cnt++;
    n >>>= 2;
  }
  return cnt;
}

更有效的变体:

public static int count11(long n) {
  int cnt = 0;
  while (n != 0) {
    switch ((int)(n & 0x3F)) {
    case 0x3F: cnt += 3; break;
    case 0x3C: case 0x33: case 0xF: cnt += 2; break;
    case 0x30: case 0xC: case 3: cnt++;
    }
    n >>>= 6;
  }
  return cnt;
}
于 2012-04-28T20:04:06.530 回答