博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Number of 1s
阅读量:4184 次
发布时间:2019-05-26

本文共 804 字,大约阅读时间需要 2 分钟。

Count the number of set bits for an 32 bits integer. How to improve the process for the second time use if the memory is unlimited?

-------------------------------------------

Tricky Solution:

uint bit_count(uint value){
printf("0x%08X has ", value, value); value = (value & 0x55555555) + ((value & 0xaaaaaaaa) >> 1); value = (value & 0x33333333) + ((value & 0xcccccccc) >> 2); value = (value & 0x0F0F0F0F) + ((value & 0xF0F0F0F0) >> 4); value = (value & 0x00FF00FF) + ((value & 0xFF00FF00) >> 8); value = (value & 0x0000FFFF) + ((value & 0xFFFF0000) >> 16); printf("%d bits set.\n", value); return value;}
General solution:

int count=0; while(n>0){   //n-1 will set the right most set bit to zero. AND with the same number will sustain the remaining bits   n&=n-1;   count++; }

转载地址:http://vwboi.baihongyu.com/

你可能感兴趣的文章
将十进制整数转换为字符串实现(Go)
查看>>
Go fmt.Println函数:将数据打印到控制台
查看>>
Linux mv命令:重命名文件
查看>>
Flask render_template函数
查看>>
整数反转(Python,LeetCode)
查看>>
CentOS修改主机名
查看>>
Python list remove方法
查看>>
整数反转(Go, LeetCode)
查看>>
查询Git版本
查看>>
Shell关系运算符
查看>>
Git配置用户信息
查看>>
删除Linux用户
查看>>
Python list pop方法:弹出列表内的元素
查看>>
Python调用C程序
查看>>
Go标识符
查看>>
Git移动文件,重命名文件
查看>>
Go errors.New函数:创建错误对象
查看>>
Go操作符和分隔符
查看>>
Linux rmdir命令:删除空目录
查看>>
制作Python3的docker镜像
查看>>