top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

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

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

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
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.

2 Answers

+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 :)

answer Nov 5, 2014 by Arshad Khan
0 votes
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;
}
answer Nov 8, 2014 by Neeraj Mishra
Similar Questions
+3 votes

So, I read the blurb that strongly advises against doing an iso-based fedup, and strongly encouraging a network-based fedup in order to yank in all the updates at once.

I have a bunch of machines to upgrade to both the workstation and server products. Having each one download everything it needs, is going to get real old.

In the past I simply rsync-ed the installation image. I have plenty of disk space on the LAN. Then I just fedup-ed everything from my rsynced image. This was almost the most efficient way to get everything updated.

Is there a single repository that I can keep rsync-ing regularly, and use it to upgrade my machines “ to both workstation and server products“ over a period of time?

+2 votes

Which is the most efficient (i.e. processing speed) way to create a server application that accesses a database: A Servlet using JDBC; a JSP page using a JavaBean to carry out the db access; or JSP combined with a Servlet? Are these my only choices?

...