Created
February 7, 2014 02:36
-
-
Save twmht/8856543 to your computer and use it in GitHub Desktop.
Count set bits in an integer(http://www.geeksforgeeks.org/count-set-bits-in-an-integer/)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Brian Kernighan’s Algorithm: | |
/* | |
Subtraction of 1 from a number toggles all the bits (from right to left) till the rightmost set bit(including the righmost set bit). So if we subtract a number by 1 and do bitwise & with itself (n & (n-1)), we unset the righmost set bit. If we do n & (n-1) in a loop and count the no of times loop executes we get the set bit count. | |
Beauty of the this solution is number of times it loops is equal to the number of set bits in a given integer. | |
*/ | |
#include<stdio.h> | |
/* Function to get no of set bits in binary | |
representation of passed binary no. */ | |
int countSetBits(int n) | |
{ | |
unsigned int count = 0; | |
while (n) | |
{ | |
n &= (n-1) ; | |
count++; | |
} | |
return count; | |
} | |
/* Program to test function countSetBits */ | |
int main() | |
{ | |
int i = 9; | |
printf("%d", countSetBits(i)); | |
getchar(); | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Simple Method Loop through all bits in an integer, check if a bit is set and if it is then increment the set bit count. See below program*/ | |
/* Function to get no of set bits in binary | |
representation of passed binary no. */ | |
int countSetBits(unsigned int n) | |
{ | |
unsigned int count = 0; | |
while(n) | |
{ | |
count += n & 1; | |
n >>= 1; | |
} | |
return count; | |
} | |
/* Program to test function countSetBits */ | |
int main() | |
{ | |
int i = 9; | |
printf("%d", countSetBits(i)); | |
getchar(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment