当前位置:网站首页>剑指 Offer 15. 二进制中1的个数
剑指 Offer 15. 二进制中1的个数
2022-04-21 20:59:00 【小刘好好学习】
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 的个数(也被称为 汉明重量).)。
示例 1:输入:n = 11 (控制台输入 00000000000000000000000000001011)输出:3
示例 2:输入:n = 128 (控制台输入 00000000000000000000000010000000)输出:1
方法一:逐位判断
- 根据 与运算 定义,设二进制数字 n ,则有:
- 若 n \& 1 = 0,则 n 二进制 最右一位 为 0 ;
- 若 n \& 1 = 1 ,则 n 二进制 最右一位 为 1 。
- 根据以上特点,考虑以下 循环判断 :
- 判断 n 最右一位是否为 1 ,根据结果计数。
- 将 n 右移一位(本题要求把数字 nn 看作无符号数,因此使用 无符号右移 操作)。
算法流程:
- 初始化数量统计变量count=0 。
- 循环逐位判断: 当 n = 0时跳出。
- count += n & 1 : 若 n & 1 == 1,则统计数 count加一。
- n >>= 1 : 将二进制数字 n 无符号右移一位
- 返回统计数量 count 。
int hammingWeight(uint32_t n) {
int count=0;
int i=32;
while(i--){
if(n&1==1){
count++;}
n>>=1;
}
return count;
}
复杂度分析:
- 时间复杂度:O(1)
- 空间复杂度:O(1)
方法二:巧用 n \& (n - 1)n&(n−1)
- (n - 1) 解析: 二进制数字 n 最右边的 1 变成 0 ,此 1 右边的 0 都变成1 。
- n&(n−1) 解析: 二进制数字 n 最右边的 1 变成 0 ,其余不变。

算法流程:
- 初始化数量统计变量 res 。
- 循环消去最右边的 1 :当 n=0 时跳出。
- res += 1 : 统计变量加 1 ;
- n &= n - 1 : 消去数字 n 最右边的 1 。
- 返回统计数量 res 。
int hammingWeight(uint32_t n) {
int count=0;
int i=32;
while(n)
{
n=n&(n-1);
count++;
}
return count;
}
复杂度分析:
- 时间复杂度 O(M) :
- 空间复杂度 O(1) :
版权声明
本文为[小刘好好学习]所创,转载请带上原文链接,感谢
https://blog.csdn.net/yahouhou_/article/details/124325900
边栏推荐
- 10.2 concentration
- 25. < tag array and simulation > - LT - 31 Next permutation + LT - 556 Next larger element III
- 工作流引擎 参数设置及业务引擎
- SQL 错误: ORA-01428: 参数 ‘0‘ 超出范围 01428. 00000 - “argument ‘%s‘ is out of range“
- 工作流操作说明
- 通達OA系統對接 單點登錄平臺使用和開發手册
- TGIP-CN 038 报名|深度解析 Apache Pulsar 源码阅读正确姿势(一)
- Connection between Tongda OA and third-party app
- 父子进程间通信(一) —— 管道的作用原理 + 管道创建函数pipe
- Module-3: Outsourcing student management system architecture design document
猜你喜欢
随机推荐
SQL 错误: ORA-01428: 参数 ‘0‘ 超出范围 01428. 00000 - “argument ‘%s‘ is out of range“
2022起重机械指挥考试题模拟考试题库及答案
Sketch
工作流报表设置 定制开发
String. Length () and string getBytes(). Length difference
Oracle column to row, splitting a field into multiple columns
《ROS2机器人建模URDF》8.4控制移动机器人轮子运动
Guanglianda is positioned as a digital "enabler"
10 minute quick start RDS
88% of industrial people don't know that these 7 points of small programs can make the revenue surge, rough and effective! It is strongly recommended to collect and read repeatedly!
About c34d
其它——CGI,FastCGI,WSGI,uWSGI,uwsgi一文搞懂
无人机组装调试教程
Live555学习
信息学奥赛一本通 1210:因子分解 | OpenJudge 1.13 22:因子分解
Trie(字典树)
APM 行业认知系列 - 十六
其它——DevOps简介
vxworks学习
工作流操作说明






