计算一个数的二进制中1的个数
//C与指针5.2
1 #include<stdio.h> 2 3 #include<stdlib.h> 4 5 6 7 int main() 8 9 { 10 11 int num = 0; 12 13 int result = 0; 14 15 printf("请输入一个数:\n"); 16 17 scanf("%d",&num); 18 19 result = count_one_bits(num); 20 21 printf("%d的二进制数中1的个数为:%d个1\n",num,result); 22 23 return 0; 24 25 } 26 int count_one_bits(unsigned int num) 27 28 { 29 30 int count = 0; 31 32 while(num) 33 34 { 35 36 num = num&(num-1); 37 count++; 38 39 40 } 41 42 return count; 43 44 }
运行结果:
posted on 2018-02-28 10:55 yiludaifei 阅读(194) 评论(0) 编辑 收藏 举报