网络问题,无法上传图片
方法1: 这道题目和190题思路一样,所以方法1我采用的就是190题的方法。时间复杂1,空间复杂1.
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res = 0;
for(int i = 0; i < 32; i++){
if((n & 1) == 1) res++;
n >>= 1;
}
return res;
}
}
方法2: 方法1的优化,n & n-1可以使n的最后一位1置0。时间复杂1,空间复杂1.
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res = 0;
while(n != 0){
res++;
n &= (n-1);
}
return res;
}
}
总结:
- 无
这篇博客探讨了两种计算整数汉明重量(即二进制表示中1的个数)的方法。方法1通过循环检查每一位,而方法2利用位运算n&(n-1)来优化,更快地将末尾的1置0。两种方法的时间复杂度均为O(1),空间复杂度为O(1)。
557





