写一个函数返回参数二进制中 1 的个数
2018-04-11 22:14
260 查看
思路一:一个数取模的结果就是最低比特位,如果取模是1,则计数。然后把这个数除以2(即去掉最低比特位),再判断。
但是这个程序有局限性,只能判断正数。
#include<stdio.h>
#include<windows.h>
int countBit(int i)
{ int c = 0;
while (i)
{ if (i % 2 == 1)//判断最低比特位
{
c++;
}
i/= 2;//去掉最低比特位 }
return c;
}
int main()
{
int i = 254;
int c = countBit(i);
printf("%d", c);
system("pause");
return 0;
}思路二:把这个数与1按位与(两个操作数同时为1,&结果为1),然后再右移移位,再判断其他位。但是这个方法必须循环32次。
#include<stdio.h>
#include<windows.h>
int countBit(int i)
{
int c = 0;
int n = 0;
while (n<32)
{
if (i&1)//判断最低比特位
{
c++;
}
i >>= 1;//去掉最低比特位
n++;
}
return c;
}
int main()
{
int i = 254;
int c = countBit(i);
printf("%d", c);
system("pause");
return 0;
}
三(最优方法):把这个数减一,再&1
#include<stdio.h>
#include<windows.h>
int count_one_bits(unsigned int value)
{
int count = 0;
while (value)
{
value = value&(value - 1);
count++;
}
return count;//通过return返回,只能返回一个值,并且返回执行权。
}
int main()
{
int value = 254;
int count = count_one_bits(value);
printf("二进制中1的个数:%d\n", count);
system("pause");
return 0;
}
程序运行后结果为:7.
但是这个程序有局限性,只能判断正数。
#include<stdio.h>
#include<windows.h>
int countBit(int i)
{ int c = 0;
while (i)
{ if (i % 2 == 1)//判断最低比特位
{
c++;
}
i/= 2;//去掉最低比特位 }
return c;
}
int main()
{
int i = 254;
int c = countBit(i);
printf("%d", c);
system("pause");
return 0;
}思路二:把这个数与1按位与(两个操作数同时为1,&结果为1),然后再右移移位,再判断其他位。但是这个方法必须循环32次。
#include<stdio.h>
#include<windows.h>
int countBit(int i)
{
int c = 0;
int n = 0;
while (n<32)
{
if (i&1)//判断最低比特位
{
c++;
}
i >>= 1;//去掉最低比特位
n++;
}
return c;
}
int main()
{
int i = 254;
int c = countBit(i);
printf("%d", c);
system("pause");
return 0;
}
三(最优方法):把这个数减一,再&1
#include<stdio.h>
#include<windows.h>
int count_one_bits(unsigned int value)
{
int count = 0;
while (value)
{
value = value&(value - 1);
count++;
}
return count;//通过return返回,只能返回一个值,并且返回执行权。
}
int main()
{
int value = 254;
int count = count_one_bits(value);
printf("二进制中1的个数:%d\n", count);
system("pause");
return 0;
}
程序运行后结果为:7.
相关文章推荐
- 1. 给定两个整形变量的值,将两个值的内容进行交换。 2. 不允许创建临时变量,交换两个数的内容(附加题) 3. 求10 个整数中最大值。 4. 写一个函数返回参数二进制中 1 的个数
- 1.写一个函数返回参数二进制中 1 的个数 比如: 15 0000 1111 4 个 1 程序原型: int count_one_bits(unsigned int valu
- 写一个函数返回参数二进制中1的个数
- 用C语言编写一个函数返回参数二进制中 1 的个数(3种方法)(谷歌笔试题)
- 求十个数中的最大的数,写一个函数返回一个参数中二进制形式中1的个数。
- 1. 给定两个整形变量的值,将两个值的内容进行交换。 2. 不允许创建临时变量,交换两个数的内容(附加题) 3. 求10 个整数中最大值。 4. 写一个函数返回参数二进制中 1 的个数
- 1、写一个函数返回参数二进制中 1 的个数(三种方法)2、获取一个数二进制序列中所有的偶数位和奇数位,分别输出二进制序列3、输出一个整数的每一位。4、两个int(32位)整数m和n的二进制表达中,有多
- 写一个函数返回参数二进制中 1 的个数
- 写一个函数返回参数二进制中 1 的个数 比如: 15 0000 1111 4 个 1
- 写一个函数返回参数二进制中 1 的个数
- 用一个函数返回参数二进制中1的个数
- 写一个函数返回参数二进制中 1 的个数
- 我用C语言 写一个函数返回参数二进制中 1 的个数的三种不同方法
- 写一个函数返回参数二进制中 1 的个数
- 一个函数返回参数二进制中的1的个数
- 写一个函数返回参数二进制中 1 的个数
- 写一个函数返回参数二进制中 1 的个数
- 写一个函数返回参数二进制中 1 的个数
- 一个函数返回参数二进制中1的个数
- 写一个函数,返回参数中二进制里 1 的个数