Reputation: 3858
I have a long number. Now what I want is following (given in pseudo code) ,
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)
Can anybody help me how to do this efficiently in Java ?
Upvotes: 1
Views: 108
Reputation: 200168
public static int count11(long n) {
int cnt = 0;
while (n != 0) {
if ((n & 3) == 3) cnt++;
n >>>= 2;
}
return cnt;
}
The even more efficient variant:
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;
}
Upvotes: 2