RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
写一个函数返回参数二进制中1的个数(三种方法)

1.运用了除法,取余方式递推出结构
2.运用右移符(>>)运算
3.利用算术与(&)运算

我们提供的服务有:成都网站建设、成都网站制作、微信公众号开发、网站优化、网站认证、魏都ssl等。为上1000家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的魏都网站制作公司

三种方法效率越来越高,减少成本

#include

int Number1(int n)
{
    int k;
    int count=0;
    while (n > 0)
    {
        k = n % 2;
        n /= 2;
        if (1 == k)
        {
            count++;
        }
    }
    return count;
}

int Number2(int n)
{
    int count = 0;
    while (n>0)
    {
        if ((n & 1) == 1)
        {
            count++;
        }
        n = n >>1 ;
    }
    return count;
}

int Number3(int n)
{
    int count = 0;
    while (n)
    {
        n = n&(n - 1);
        count++;
    }
    return count;
}
int main()
{
    int n;
    printf("请输入一个数:\n");
    scanf("%d",&n);
    int ret1=Number1(n);
    printf("%d\n",ret1);
    int ret2 = Number2(n);
    printf("%d\n",ret2);
    int ret3 = Number3(n);
    printf("%d\n",ret3);
    system("pause");
    return 0;
}

当前文章:写一个函数返回参数二进制中1的个数(三种方法)
文章路径:http://scyingshan.cn/article/pdjoih.html