# What would be most efficient way to find number of 1 in a variables?

+1 vote
88 views
What would be most efficient way to find number of 1 in a variables?
posted Nov 3, 2014

Didn't get you, can you please elaborate the question with sample input and your expected output.
Say the input is 00110011 then the output should be 4 as number of one's in the number is 4.

+1 vote

Use bit wise and operator (&) with 1 on you number. Do this on each bit of your number.
Here is my C program (Tested).

#include <stdio.h>

int num_ones_present(int num)
{
int i = 0;

while (num) {
i += (num & 1);  //It will return 1 if num's 0th bit is 1 else return 0.
num >>= 1;
}

return i;
}

int main()
{
int num, next_num, i = 0;
int num_ones = 0;

printf("Enter the number : ");
scanf("%d", &num);

num_ones = num_ones_present(num);
printf("Then given number is : %d which has %d num of 1's\n", num, num_ones);

return 0;
}

Happy Coding :)

int main()
{
int count = 0,x;
printf("Enter Number\n");
scanf("%d",&x);
while(x)
{
count++;
x = x & x-1;
}
printf("Number of on bits[%d]\n", count);
return 0;
}
Similar Questions

Input: 23678210
Output: 8