C语言二进制中1的个数(代码实例)
程序员文章站
2022-03-23 19:33:26
二进制中1的个数
//第一种:短除法
int count_one(unsigned num)
{
int count = 0;
while (num != 0)
{
if...
二进制中1的个数
//第一种:短除法 int count_one(unsigned num) { int count = 0; while (num != 0) { if (num % 2 == 1) { count++; } num /= 2; } return count; } ? //第二种:移位按位与1法 int count_one(int num) { int count = 0; int i = 0; for (i = 0; i < 32; i++) { count += (num >> i) & 1; } return count; } ? //第三种:num与num-1进行按位与 int count_one(int num) { int count = 0; while (num != 0) { num = num & (num - 1); count++; } return count; } ? int main() { int num = 0; int count = 0; printf("请输入一个数字>:"); scanf("%d", &num); count = count_one(num); printf("1的个数为:%d\n", count); return 0; }