本文共 535 字,大约阅读时间需要 1 分钟。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>#include<stdlib.h>Fun1(int a) //用移位的方法{ int i = 0;int count1 = 0;for (i = 0; i < 32; i++){ if ((a>>i)&1==1){ count1++;}}return count1;}Fun2(int a) //用n&(n-1)的方法 循环了几次就有几个1{ int count2 = 0;while (a){ a=a&(a - 1);count2++;}return count2;}int main(){ int a = 0;printf("请输入一个二进制数\n");scanf("%d", &a);int count1 = Fun1(a);printf("%d\n", count1);int count2 = Fun2(a);printf("%d\n", count2);system("pause");return 0;}转载于:https://blog.51cto.com/14239789/2377431