当前位置:网站首页>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;
}
};
关于位运算(按位与、按位或、异或)可看 位运算(按位与、按位或、异或)
边栏推荐
- leetcode 899. 有序队列
- 友宏医疗与Actxa签署Pre-M Diabetes TM 战略合作协议
- 从文本匹配到语义相关——新闻相似度计算的一般思路
- Go语言为任意类型添加方法
- 谁的孙子最多II
- glide set gif start stop
- The sword refers to Offer II 044. The maximum value of each level of the binary tree-dfs method
- 化算力为战力:宁夏中卫的数字化转型启示录
- matplotlib画polygon, circle
- Network protocol-TCP, UDP difference and TCP three-way handshake, four wave
猜你喜欢
随机推荐
阿洛的反思
Mapper输出数据中文乱码
php截取中文字符串实例
极验深知v2分析
子树的大小
ECCV2022 | 用于视频问题回答的视频图Transformer
leetcode 136. 只出现一次的数字(异或!!)
基础软件与开发语言开源论坛| ChinaOSC
嵌入式分享合集27
子结点的数量(2)
染料修饰核酸RNA|[email protected] 610/[email protected] 594/Alexa 56
tRNA甲基化偶联3-甲基胞嘧啶(m3C)|tRNA-m3C (3-methylcy- tidine)
RNA核糖核酸修饰Alexa 568/[email protected] 594/[email prote
codeforces:C. Maximum Subrectangle【前缀和 + 贪心 + 最小子数组和】
xss.haozi练习通关详解
消除对特权账户的依赖使用Kaniko构建镜像
JWT详解
为什么 BI 软件都搞不定关联分析
Detailed AST abstract syntax tree
高并发,你真的理解透彻了吗?









