A binary integer count the number of 1s

method one:

Comparison of methods of violence (obtained by binary right):

int _Count(int x)
{
    int cnt = 0;
    while(x)
    {
        cnt += x&1;
        x >>= 1;
    }
    return cnt;
}

Method Two:

Through this number and the phase ratio of the numbers of his small :( 1 is a magical way to manually write a few examples can be seen, but if they want to, it is quite laborious)

int _Count(int x)
{
    int cnt = 0;
    while(x)
    {
        x &= (x-1);
        cnt++;
    }
    return cnt;
}

 

Guess you like

Origin www.cnblogs.com/sykline/p/10959277.html