Solution #1: The most straightforward approach is to check each bit one by one. Here is the code,
Solution #2: The below code is an efficient version which improves the average time,
int count1(int n)
{
int count=0;
while(n)
{
if(n&1)
count++;
n = n>>1;
}
return count;
}
Solution #2: The below code is an efficient version which improves the average time,
int count2(int n)
{
int count=0;
while(n)
{
count++;
n = n&(n-1);
}
return count;
}
No comments:
Post a Comment