找32位整数中二进制1的个数
#include<stdio.h>
#include<string.h>
#include<malloc.h>
int count(int n);
int main() {
int n;
while (scanf("%d", &n) != EOF) {
printf("%d", count(n));
}
return 0;
}
/*
* Function:给定一个32位整数n,返回该整数二进制形式1的个数
* Input:32位整数n
* Return:二进制形式1的个数
*/
int count(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
result += n & (1U << i) ? 1 : 0;
}
return result;
}