当前位置:网站首页>Leetcode sword refers to Offer 15. 1 in the binary number
Leetcode sword refers to Offer 15. 1 in the binary number
2022-08-03 20:11:00 【Luna programming】
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为 汉明重量).).
示例 1:
输入:n = 11 (控制台输入 00000000000000000000000000001011)
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’.
提示:
输入必须是长度为 32 的 二进制串 .
思路一:& 和 >> (使用 按位与 和 右移运算符 逐位判断)
时间复杂度:O(n)
空间复杂度:O(1)
class Solution {
public:
int hammingWeight(uint32_t n) {
int sum=0;
while(n){
sum+=(n&1); // (n&1) is to determine whether the last digit is1.按位与的运算规则是:2Only in the corresponding position of the base number2numbers are1,结果才为1
//因为1the binary representation of 32Only the last of the bits is1,所以前31Bitwise AND is followed by both0,Then it is to judge whether the last bit is all1,若都是1则为真, (n&1) 的值为1,否则为0
n>>=1; //右移1bit delete the last bit,高位正数补0,负数补1
}
return sum;
}
};
思路二:使用 n&(n-1)
class Solution {
public:
int hammingWeight(uint32_t n) {
int sum=0;
while(n){
n&=(n-1); //每一次的 n&=(n-1) 都将32rightmost of the bits1变为0,直到最后n为0
++sum;
}
return sum;
}
};
关于位运算(按位与、按位或、异或)可看 位运算(按位与、按位或、异或)
边栏推荐
猜你喜欢
List类的超详细解析!(超2w+字)
盘点在线帮助中心对企业能够起到的作用
化算力为战力:宁夏中卫的数字化转型启示录
小马智行起诉擎天智卡:索赔6000万 彭军称要斗争到底
宁德时代2号人物黄世霖辞任副董事长:身价1370亿
【leetcode】剑指 Offer II 009. 乘积小于 K 的子数组(滑动窗口、双指针)
百利药业IPO过会:扣非后年亏1.5亿 奥博资本是股东
Internet Download Manager简介及下载安装包,IDM序列号注册问题解决方法
高性能计算软件与开源生态| ChinaOSC
RNA核糖核酸修饰RNA-HiLyte FluorTM 405荧光染料|RNA-HiLyte FluorTM 405
随机推荐
嵌入式分享合集27
EasyCVR平台海康摄像头语音对讲功能配置的3个注意事项
leetcode 899. 有序队列
李沐动手学深度学习V2-BERT微调和代码实现
leetcode 16.01. 交换数字(不使用临时变量交换2个数的值)
Go语言类型与接口的关系
自定义form表单验证
Matlab paper illustration drawing template No. 42 - bubble matrix diagram (correlation coefficient matrix diagram)
php截取中文字符串实例
Auto.js实现朋友圈自动点赞
LeetCode 1374. 生成每种字符都是奇数个的字符串
开源教育论坛| ChinaOSC
JMeter笔记5 |Badboy使用和录制
JS 内置构造函数 扩展 prototype 继承 借用构造函数 组合式 原型式creat 寄生式 寄生组合式 call apply instanceof
Detailed demonstration pytorch framework implementations old photo repair (GPU)
C中的数据存储
leetcode 326. 3 的幂
多模态 参考资料汇总
力扣206-反转链表——链表
leetcode 125. 验证回文串