标签:二进制数中1的个数
写一个函数返回参数二进制中 1 的个数
比如: 15 0000 1111 4 个 1
程序原型:
int count_one_bits(unsigned int value)
{
// 返回 1的位数
}
方法一:(模除)缺点;未考虑十进制是负数的情况,例-1则bit=0 #include<stdio.h> #include<stdlib.h> int main() { int count = 0; int num = -1; scanf("%d", &num); while (num) { if (num % 2 == 1) { count++; } num = num / 2; } printf("count= %d\n", count); system("pause"); return 0; }
方法二:(按位与和移位)
int main() { int count = 0; int num = 15; int i = 32; while (i) { if (num & 1 == 1) { count++; } num = num / 2; num = num >> 1; i -= 1; } printf("count= %d\n", count); system("pause"); return 0; }
方法三:(x=x&(x-1))
#include <stdio.h> int main() { int count = 0; int num = 0; scanf("%d",&num); while(num) { count++; num = num & (num-1);//有多少个1 } printf("count = %d\n",count); return 0; }
附:
(1)num=x&(x-1)判断是否是2^n,则num=(num-1)&num是否为00即可
(2)int count_one_bits(unsigned int value),正数不需要考虑补码,负数需要考虑补码,
unsigned int value巧妙之处在于负数也可以使用
本文出自 “小灰灰” 博客,请务必保留此出处http://10742910.blog.51cto.com/10732910/1719787
标签:二进制数中1的个数
原文地址:http://10742910.blog.51cto.com/10732910/1719787