博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】191. Number of 1 Bits 正整数中的bit位为1的个数
阅读量:6935 次
发布时间:2019-06-27

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

1. 题目

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

Credits:

Special thanks to for adding this problem and creating all test cases.

2. 思路

第一反应是直接用x & (x-1)的循环到x=0来算。第二反应是分字节的查表法。

代码之美的第10章“寻找快速的种群计数”有更深入的讲解,用了其中的最优的方法。

按位计算,第一次是奇偶位相加放在每两位的地方。然后每4位的两位两位相加,放在每4位的结果上。知道32位的每16位相加。由于最多只有32个1,也就是只有低位的5bit有效,后面的8、16的不用再移位计算,溢出的高位部分无所谓,最后用&清0即可。

3. 代码

class Solution {public:    int hammingWeight(uint32_t n) {        n = n - ((n>>1) & 0x55555555);        n = (n & 0x33333333) + ((n>>2) & 0x33333333);        n = (n + (n>>4)) & 0x0f0f0f0f;        n = n + (n>>8);        n = n + (n>>16);        return n & 0x3f;    }};

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

你可能感兴趣的文章
挨踢项目求生法则-需求篇
查看>>
centos搭建ntp服务器
查看>>
mysql一个冷门参数引起的同步故障
查看>>
dreamweaver中基本代码的含义
查看>>
云端保护刻不容缓
查看>>
php安装memcached扩展:
查看>>
第4章 部署模式 Deployment Plan(部署规划)
查看>>
Navicat for MySQL使用手记(中)--导入/导出数据表
查看>>
互动交流:移动系统安全研究专题及用户关心的焦点问题调研
查看>>
我的友情链接
查看>>
去哪儿网支付系统架构演进(下篇)
查看>>
./configure: error: the HTTP rewrite module requires the PCRE library
查看>>
使用AzCopy命令行工具上传VHD
查看>>
使用Windows Azure 第一步就应该创建地缘组Affinity groups
查看>>
征询一下意见
查看>>
微信内置浏览器不支持APK附件下载的原因
查看>>
前端性能优化(一):桌面浏览器前端优化策略
查看>>
Linux下批量修改文件编码
查看>>
添加反爬策略1-User-Agent
查看>>
10、程序员和编译器之间的关系
查看>>