统计整数二进制表示中1的个数
来源:互联网 发布:产品经理用app 知乎 编辑:程序博客网 时间:2024/06/05 19:38
三种比较好的方法:
(1)复杂度为
int test(int n){ int count=0; while(n != 0){ count += n&1; n >>= 1; } return count;}
(2)
int test(int n){ int count=0; while(n != 0){ n &= n-1; count ++; } return count;}(3)
int test(int n){ n = (n&0x55555555) + ((n>>1)&0x55555555); n = (n&0x33333333) + ((n>>2)&0x33333333); n = (n&0x0f0f0f0f) + ((n>>4)&0x0f0f0f0f); n = (n&0x00ff00ff) + ((n>>8)&0x00ff00ff); n = (n&0x0000ffff) + ((n>>16)&0x0000ffff); return n;}
比如这个例子,143的二进制表示是10001111,这里只有8位,高位的0怎么进行与的位运算也是0,所以只考虑低位的运算,按照这个算法走一次
+---+---+---+---+---+---+---+---+
| 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | <---143
+---+---+---+---+---+---+---+---+
| 0 1 | 0 0 | 1 0 | 1 0 | <---第一次运算后
+-------+-------+-------+-------+
| 0 0 0 1 | 0 1 0 0 | <---第二次运算后
+---------------+---------------+
| 0 0 0 0 0 1 0 1 | <---第三次运算后,得数为5
+-------------------------------+
0 0
- 统计整数的二进制表示中1的个数
- 统计整数n的二进制表示中1的个数
- 统计整数二进制表示中1的个数
- C语言 统计整数二进制表示中1的个数
- c语言 统计整数二进制表示中1的个数
- 统计整数二进制表示中1的个数
- 统计整数二进制表示中1的个数
- 统计整数二进制表示中1的个数
- 统计整数二进制表示中1的个数
- 统计整数二进制表示中1的个数
- C语言 统计整数二进制表示中1的个数
- 统计整数二进制表示中1的个数
- 统计整数二进制表示中1的个数
- 整数二进制表示中1的个数
- 整数二进制表示中1的个数
- 整数二进制表示中1的个数
- 整数二进制表示中1的个数
- 整数二进制表示中1的个数
- 常用的渗透测试工具型网站
- MapReduce and MPP: Two sides of the Big Data coin?
- 程序设计作业报告项目一
- 错误Communications link failure,The last packet successfully received from the server was的解决方法
- 数值转换工具 TypedValue ---屏幕单位转换 (笔记 )
- 统计整数二进制表示中1的个数
- 流读取数据的时候字符乱码的终极解决办法。
- 大精进
- CentOS 64位系统下 PHP 5.3.3 启动 php-fpm 功能的安装
- 泡沫对话框
- Orace数据库锁表的处理与总结<摘抄与总结一>
- android 4.4 信息设置默认
- Android_系统工具_draw9patch超详细教程制作.9.png
- 移动应用大数据分析平台搭建杂谈