题目:输入一个整数,求该整数的二进制表达式中有多少个1
例如,输入10,由于其二进制表示为1010,有两个1,因此输出2
此题考察位运算,微软曾经用过这道题
xxxx1000 & (xxxx1000-1) = xxxx0000
#include<stdio.h>
int count1(int n) {
int c=0;
while(n!=0) {
n = n&(n-1);
c++;
}
return c;
}
int main() {
int a=16;
printf("%d\n",count1(a));
}