当前位置:网站首页>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;
}
};
关于位运算(按位与、按位或、异或)可看 位运算(按位与、按位或、异或)
边栏推荐
- Use ControlTemplate or Style from resource file in WPF .cs and find the control
- EasyCVR平台海康摄像头语音对讲功能配置的3个注意事项
- ESP8266-Arduino编程实例-MCP4725数模转换器驱动
- 简易电子琴设计(c语言)
- 高性能计算软件与开源生态| ChinaOSC
- Detailed steps for tensorflow-gpu2.4.1 installation and configuration
- 微导纳米IPO过会:年营收4.28亿 君联与高瓴是股东
- 149. 直线上最多的点数-并查集做法
- 单调栈及其应用
- 【飞控开发高级教程4】疯壳·开源编队无人机-360 度翻滚
猜你喜欢

那些年我写过的语言
[email protected] 610/[email protected] 594/Alexa 56"/>染料修饰核酸RNA|[email protected] 610/[email protected] 594/Alexa 56

华为设备配置VRRP负载分担

调用EasyCVR云台控制接口时,因网络延迟导致云台操作异常该如何解决?

2022 年值得尝试的 7 个 MQTT 客户端工具

Internet Download Manager简介及下载安装包,IDM序列号注册问题解决方法

从文本匹配到语义相关——新闻相似度计算的一般思路

力扣707-设计链表——链表

1161 最大层内元素和——Leetcode天天刷【BFS】(2022.7.31)

转运RNA(tRNA)甲基化修饰7-甲基胞嘧啶(m7C)|tRNA-m7G
随机推荐
EasyCVR平台海康摄像头语音对讲功能配置的3个注意事项
alicloud3搭建wordpress
C51 存储类型与存储模式
盘点在线帮助中心对企业能够起到的作用
LeetCode 1374. 生成每种字符都是奇数个的字符串
8.2模拟赛总结
多模态 参考资料汇总
边缘盒子+时序数据库,美的数字化平台 iBuilding 背后的技术选型
ECCV 2022 Oral | 满分论文!视频实例分割新SOTA: IDOL
利用 rpush 和 blpop 实现 Redis 消息队列
ES6解构赋值--数组解构及对象解构
ESP8266-Arduino编程实例-WS2812驱动
「学习笔记」高斯消元
【STM32】标准库-自定义BootLoader
高并发,你真的理解透彻了吗?
头条服务端一面经典10道面试题解析
按需视觉识别:愿景和初步方案
C中的数据存储
Hinton2022年RobotBrains访谈记录
In-depth understanding of JVM-memory structure