Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

counting number of ones in binary representation of a number [duplicate]

Tags:

java

Possible Duplicate:
Best algorithm to count the number of set bits in a 32-bit integer?

I want to find out how many 1s are there in binary representation of a number.I have 2 logic .

  1.   int count =0;
    int no = 4;
    
    while(no!=0){
        int d = no%2;
        if(d==1)
            count++;
        no = no/2;
        str = str+ d;
    }
    
  2. Now second logic is to keep on masking number iteratively with 1,2,4,8,32 and check if result is 1,2,4, 8..... Am not geting what should be ending condition for this loop.

like image 351
akshayxyz Avatar asked Mar 11 '11 00:03

akshayxyz


People also ask

How many 1s are there in binary?

∴ The total number of 1's is 8.


2 Answers

We can make use of overflow for your loop:

int count = 0;
int number = 37;
int mask = 1;

while(mask!=0)
{
    int d = number & mask;
    if(d != 0)
        count++;
    /* Double mask until we overflow, which will result in mask = 0... */
    mask = mask << 1;
    str = str+ d;
}
like image 186
Heath Hunnicutt Avatar answered Oct 15 '22 17:10

Heath Hunnicutt


Use Java API(java 5 or above).

Integer.bitCount(int);
Long.bitCount(long);

NOTE: The above java methods are based on hacker's delight

like image 41
Prince John Wesley Avatar answered Oct 15 '22 17:10

Prince John Wesley