Skip to content

Instantly share code, notes, and snippets.

@KushalP
Created April 12, 2010 18:45
Show Gist options
  • Save KushalP/363873 to your computer and use it in GitHub Desktop.
Save KushalP/363873 to your computer and use it in GitHub Desktop.
#include <stdio.h>
int bit_count(int n);
int main()
{
int i, limit = 255;
for (i = 0; i <= limit; i++)
{
printf("Input: %d\tBit Count: %d\n", i, bit_count(i));
}
return 0;
}
int bit_count(int n)
{
int count = 0;
while (n)
{
count += n % 2; // If we've got an odd number, add 1
n /= 2; // Divide by 2, rounding down
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment