当前位置:网站首页>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;
}
};
关于位运算(按位与、按位或、异或)可看 位运算(按位与、按位或、异或)
边栏推荐
- RNA核糖核酸修饰RNA-HiLyte FluorTM 405荧光染料|RNA-HiLyte FluorTM 405
- codeforces:C. Maximum Subrectangle【前缀和 + 贪心 + 最小子数组和】
- 149. The largest number on a straight line, and check the set
- pytorch框架实现老照片修复功能详细演示(GPU版)
- List类的超详细解析!(超2w+字)
- 自定义form表单验证
- EasyCVR平台海康摄像头语音对讲功能配置的3个注意事项
- 详解AST抽象语法树
- 收藏-即时通讯(IM)开源项目OpenIM-功能手册
- Go语言类型与接口的关系
猜你喜欢

算法--交错字符串(Kotlin)

收藏-即时通讯(IM)开源项目OpenIM-功能手册

边缘盒子+时序数据库,美的数字化平台 iBuilding 背后的技术选型

Detailed AST abstract syntax tree

从腾讯阿里等大厂出来创业搞 Web3、元宇宙的人在搞什么

小马智行起诉擎天智卡:索赔6000万 彭军称要斗争到底

NNLM、RNNLM等语言模型 实现 下一单词预测(next-word prediction)

ECCV 2022 Oral | 满分论文!视频实例分割新SOTA: IDOL
[email protected] 610/[email protected] 594/Alexa 56"/>染料修饰核酸RNA|[email protected] 610/[email protected] 594/Alexa 56

RNA核糖核酸修饰RNA-HiLyte FluorTM 405荧光染料|RNA-HiLyte FluorTM 405
随机推荐
【leetcode】剑指 Offer II 007. 数组中和为 0 的三个数(双指针)
Pytorch GPU 训练环境搭建
leetcode 326. 3 的幂
In-depth understanding of JVM-memory structure
LeetCode 899. 有序队列
tRNA修饰2-甲基胞嘧啶(m2C)|tRNA修饰m2G (N2-methylguanosine)
信使mRNA甲基化偶联3-甲基胞嘧啶(m3C)|mRNA-m3C
剑指 Offer II 044. 二叉树每层的最大值-dfs法
Statistical machine learning 】 【 linear regression model
第三方验收测试报告有什么作用?如何获取权威软件测试报告?
Go语言类型与接口的关系
多模态 参考资料汇总
node版本切换工具NVM以及npm源管理器nrm
Network protocol-TCP, UDP difference and TCP three-way handshake, four wave
数学之美 第六章——信息的度量和作用
Solidity智能合约开发 — 4.1-合约创建和函数修饰器
NNLM、RNNLM等语言模型 实现 下一单词预测(next-word prediction)
Benchmarking Lane-changing Decision-making for Deep Reinforcement Learning
花 30 美金请 AI 画家弄了个 logo,网友:画得非常好,下次别画了!
Anaconda 虚拟环境迁移