写一个函数返回参数二进制中 1 的个数
程序员文章站
2024-03-15 15:49:30
...
一、看 i 能和 i-1 与多少次
#include<stdio.h>
#include<stdlib.h>
int countbit(int i)
{
int c = 0;
while (i)
{
i &= (i - 1);
c++;}
return c;
}
int main()
{
int i = 254;
int c=countbit(i);
printf("%d\n", c);
system("pause");
return 0;
}
二、
int count(int i)
{
int c = 0;
while(i)
{
if (i % 2 == 1)
{
c++;
}
i /= 2;
}
return c;
}
int main()
{
int i = 10;
int c = count(i);
printf("%d\n", c);
system("pause");
return 0;
}
三
int count(int i)
{
int c = 0;
while (i)
{
if (i&1)
{
c++;
}
i>>=1;
}
return c;
}
int main()
{
int i = 10;
int c = count(i);
printf("%d\n", c);
system("pause");
return 0;
}
下一篇: 【面试题】整数N的二进制中1的个数
推荐阅读
-
函数实现返回参数二进制中1的个数——多种写法
-
写一个函数返回参数二进制中 1 的个数
-
有一个整数n,写一个函数f(n),返回0到n之间出现的"1"的个数
-
JavaScript - 写一个纯函数 - 返回字符串中的 最大值 和 最小值
-
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
-
剑指offer:输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
-
[算法]输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示
-
剑指offer:输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
-
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
-
【输入一个整数,输出该数二进制表示中1的个数,其中负数用补码表示---------【剑指offer】】