统计给二进制数有多少个1

思路

任何数和1进行与操作,都保留其末尾数

  private static void oneCount(int i) {
        int count = 0;
        while (i > 0) {
            int one = i & 1;
            if (one == 1) {
                count++;
            }
            i = i >> 1;
        }
        System.out.println(":count:" + count);
    }

 上面都解法对正数是可以对,但是对负数不行,因为负数的有符号右移最终会变成0xfff 

我们可以换个思路,

n & (n-1) 末尾会变成0

void numberof1(int n){
    int count = 0 ;
    while (n){
        count++;
        n = n & (n - 1);
    }

    printf("%d\n",count);
}

int main(){

    numberof1(1024);
}

 

posted @ 2020-06-20 16:38  冬马党  阅读(165)  评论(0)    收藏  举报