当前位置:网站首页>LeetCode 191. Number of 1 Bits(位1的个数) 位运算/easy
LeetCode 191. Number of 1 Bits(位1的个数) 位运算/easy
2022-07-27 14:05:00 【押切徹】
1.Description
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
提示:
请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3。
2.Example
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
3.Solution
1.按位右移
可以右移32次或者右移到n等于0为止。
注意:Java中的“>>”是算数右移,舍弃最低位,高位用符号位填补;
“>>>”是逻辑右移:舍弃最低位,高位用 0 填补。
因此使用第二种方法时需要使用“>>>”。
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n!=0) {
if((n&1)==1) {
count++;
}
n=n>>>1;
}
return count;
}
}
2.位运算优化
使用n = n&(n-1)可以得到将n的最低位的1变成0之后的数,因此只要循环进行操作统计一共进行了多少次操作就行了。
public class Solution {
public int hammingWeight(int n) {
int ret = 0;
while (n != 0) {
n &= n - 1;
ret++;
}
return ret;
}
}
边栏推荐
- Get the data of the first frame of unity's open camera
- STM32F103C8T6在Arduino框架下驱动ssd1306 0.96“ IIC OLED显示
- 网络设备硬核技术内幕 路由器篇 4 贾宝玉梦游太虚幻境(下)
- Unityui aspect processing (induction and accumulation)
- [ManageEngine] what is Siem
- adb命令 (安装apk包格式:adb install 电脑上apk地址包名)
- 视觉系统设计实例(halcon-winform)-9.文字显示
- Basic exercises of C language
- Construction of knowledge map of financial securities and discovery of related stocks from the perspective of knowledge relevance
- TXT把换行 替换为空格或者取消换行
猜你喜欢

Visual system design example (Halcon WinForm) -10. PLC communication

Docker practical experience: deploy mysql8 master-slave replication on docker

终于有人把面试必考的动态规划、链表、二叉树、字符串全部撸完了

2022年中国网络视频市场年度综合分析

DVWA full level customs clearance tutorial

User question understanding and answer content organization for epidemic disease Science Popularization

JS epidemic at home, learning can't stop, 7000 word long text to help you thoroughly understand the prototype and prototype chain

代码覆盖率统计神器-jacoco工具实战

Graphical SQL is too vivid

Toward fast, flexible, and robust low light image enhancement cvpr2022
随机推荐
LeetCode 81. 搜索旋转排序数组 II 二分/medium
LeetCode 781. 森林中的兔子 哈希表/数学问题 medium
LeetCode 1143. 最长公共子序列 动态规划/medium
What if win11 wallpaper turns black? The solution of win11 wallpaper blackening
NEFU117 素数个数的位数【素数定理】
关于 CMS 垃圾回收器,你真的懂了吗?
图解 SQL,这也太形象了吧
LeetCode 面试题 17.21. 直方图的水量 双指针,单调栈/hard
【ManageEngine】什么是SIEM
How to help enterprises optimize office management
Confirm the time accuracy of the power supply setting voltage through the i/o function of vn1630/vn7640
STM32F103C8T6在Arduino框架下驱动SH1106 1.3“ IIC OLED显示
网络设备硬核技术内幕 路由器篇 14 从鹿由器到路由器 (中)
Shell programming specifications and variables
网络设备硬核技术内幕 路由器篇 19 DPDK(四)
被动收入:回归原始且安全的两种赚取方法
微信小程序实现音乐搜索页面
UnityUI方面处理(归纳与积累)
If we were the developer responsible for repairing the collapse of station B that night
Redis