#include <stdio.h>
int func(int x) { 
    int countx = 0; 
    while(x) { 
        countx ++; 
        x = x & (x - 1); 
    } 
    return countx; 
} 
int main() {
    int x;
    int cnt=0;
    scanf("%d",&x);
     cnt= func(x);
    printf("%d\n",cnt);
}
嘻嘻刷题的时候遇见的代码没想到这里运用上了,学以致用嗷~
int func(int x) {
int countx = 0;
while(x) {
countx ++;
x = x & (x - 1); //求转换为二进制后,1的个数,其实还有一个是x=x|(x-1);找的是0 的个数~
}
return countx;
}

 京公网安备 11010502036488号
京公网安备 11010502036488号