方法一: 程序: #include<stdio.h> int count_one_bits(int t) { int i = 32; int count = 0; while (i>0) { if (t & 1 == 1) { count++; } //t=t/2 t = t >> 1; i -= 1; } return count; } int main() { int t = 0; printf("请输入一个整数:"); scanf("%d", &t); int ret=count_one_bits(t); printf("count=%d\n", ret); return 0; } 方法二: 程序: #include<stdio.h> int count_one_bits(int t) { int count = 0; while (t) { count++; t = t&(t - 1); //最低位为1,其余全为0,循环效率高,有几个1就循环几次 } return count; } int main() { int t = 0; printf("请输入一个整数:"); scanf("%d", &t); int ret=count_one_bits(t); printf("count=%d\n", ret); return 0; } 结果一: 请输入一个整数:15 count=4 请按任意键继续. . . 结果二: 请输入一个整数:-2 count=31 请按任意键继续. . .
写一个函数返回参数二进制中 1 的个数 比如: 15 0000 1111 4 个 1
原创文章标签 c语言 函数 返回参数二进制中 1 的 文章分类 C/C++ 后端开发
-
第五节 二进制安装docker
二进制安装docker
docker linux 开机自启 -
Linux
&n
Linux -
压抑-痛苦
今天你来了,我好开心,可是你知道嘛? 今天我也痛苦了一天,从未有过的绝望。 &nb
职场 情感 休闲 试试 -
不为彼岸只为海
不为彼岸只为海 ——————谁的青春不是诗
程序员 奋斗 黑马 java