Tuesday, December 28, 2010

Can you Count the Number of bits set in an integer ?

First method:

#include<stdio.h>
void main()
{
int i,num,sum=0;
printf("enter the number:");
scanf("%d",&num);
 while(num)
   {
   sum=sum+num%2;
   num/=2;
   }
printf("\n sum is:%d",sum);
getch();
}

Second method:

#include<stdio.h>
void main()
{
int i,num,sum=0;
printf("enter the number:");
scanf("%d",&num);
 while(num)
   {
   sum=sum+ (num & 1);
   num=num>>1;
   }
printf("\n sum is:%d",sum);
getch();
}

No comments:

Post a Comment