Thursday, January 23, 2014

find number of 1s

Q:

 Please implement a function to get the number of 1s in an integer. For example, the integer 9 is 1001 in binary, so it returns 2 since there are two bits of 1s.


A:
左移(数字1)或者右移(n),同时和1 比较 ---(下面代码是右移)
int NumberOf1(int n){
    int count = 0;
    while(n)    {
        if(n & 1)
            count ++;

        n = n >> 1;
    }
    return count;
}

tricky点儿的是  y用 n&(n-1)消去最右边的一个1.

 
int NumberOf1(int n){
    int count = 0;

    while (n){
        ++ count;
        n = (n - 1) & n;
    }

    return count;
}



No comments:

Post a Comment