#include
// number of 1s in a nibble (set of 4 bits)
// this helps in faster computation
int nibble[] = {0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};
int main() {
unsigned n = 0; // user given number
unsigned no1s = 0; // number of 1s in n
printf("Enter a number : ");
scanf("%u", &n);
while( n != 0 ) {
no1s += nibble[n&0xF]; // extract the final nibble and add the 1s in it
n = (unsigned)n>>4; // shift out the nibble that has been counted
}
printf("No of 1s in the given number is %u\n", no1s);
return 0;
}
2006-10-28 02:25:17
·
answer #1
·
answered by swami060 3
·
0⤊
0⤋
scanf("%d ",&number);//actual number
scanf("%d ",&n); // number of bits
int number_of_set_bits = 0;
for(int i=0;i<=n-1;i++)
{
if ((number >> i) & 0x01) number_of_set_bits++;
}
printf("total set bits are %d", number_of_set_bits);
The above program shifts the given number and then logical and it with the last bit. Its working.
2006-10-27 22:49:12
·
answer #2
·
answered by manoj Ransing 3
·
0⤊
0⤋