【code】找32位整数中二进制1的个数

找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;
}


发布了46 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zzy296753977/article/details/101482753