Friday, January 29, 2016

Count set bits

Count set bits


Count number of set bits in a given number. For example, given number is 10 (1010) then number of set bits is 2. given number is 15 (1111) then number of set bits is 4.
Sol:
1
2
3
4
5
6
7
8
9
10
11
int CountSetBits(int x)
{
    int count=0;
     
    while(x > 0)
    {
        count++;           
        x = x & (x-1);         
    }
    return count;
}

No comments:

Post a Comment