写一个函数返回参数二进制中 1 的个数(三种方法)

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

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

#include<stdio.h>

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;
}

猜你喜欢

转载自blog.51cto.com/14233078/2378424