方法一:count计数法
#include<stdio.h> int count_bit_one(unsigned int num)//负数的源码和补码不相同,所以把负数的二进制补码转化成对应的无符号的源码的数。正数的源码和补码相同。 { //此方法是对一个数的二进制源码进行操作的 int count = 0; while (num) { if (num % 2 == 1) { count++; } num /= 2; } return count; } int main() { int num = 0; scanf("%d", &num); printf("%d\n", count_bit_one(num)); return 0; }
方法二:按位与法(普通版)
#include<stdio.h> int count_bit_one(int num) { int i = 0; int count = 0; for (i = 0; i < 32; i++) { if (((num >> i) & 1) == 1) { count++; } } return count; } int main() { int num = 0; scanf("%d", &num); printf("%d\n", count_bit_one(num)); return 0; }
方法三:按位与法(高效率版)
#include<stdio.h> int count_bit_one(int num) { int count = 0; while (num) { count++; num = num & (num - 1);//每进行一次这个操作,num的二进制表示中就少一个1,直到最后全为0 } return count; } int main() { int num = 0; scanf("%d", &num); printf("%d\n", count_bit_one(num)); return 0; }
运行结果