- 1
How to count set bit pairs in supplied integer?
4 odpowiedzi
+ 3
RUSHIKESH S. it looks like this question was never solved. I think enough time has passed that I may supply a solution. If you shift the bits leftward by one position then bitwise & with the original number you will get a result that has 1 bit set for every original pair. Count the number of 1 bits and that will be the final answer. Check out my implementation:
#include <stdio.h>
//Brian Kernighan's favorite bit counter
unsigned int countBits(unsigned int v) {
unsigned int c;
for (c = 0; v; c++)
v &= v - 1;
return c;
}
//count pairs of adjacent 1 bits
int main() {
unsigned int n;
scanf("%u", &n);
//here is the magic!
printf("%u\n", countBits(n&n<<1));
return 0;
}
0
Set bit pairs? you mean adjacent set bits or what?
0
Yes
0
Have you tried?
How far have you gone through with this?
Or is it solved?