Question
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011
, so the function should return 3.
本题难度Easy。有2种算法分别是: 移位法 和 减一相与法
1、移位法
复杂度
时间 O(N) 空间 O(1)
思路
通过与运算符判断最低位/最高位是否是1,然后再右移/左移。重复此步骤直到原数归零。
代码
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
//require
int ans=0;
//invariant
for(int i=0;i<32;i++){
if((n&1)==1)ans++;
n>>=1;
}
//ensure
return ans;
}
}
注意
这道题说的是把n
当作 unsigned integer,但是n
仍然是signed integer。第9行写为>>>
,循环条件可以写成while(n!=0)
:
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int mark = 0b1, count = 0;
while(n != 0b0){
if((n & mark)==0b1){
count++;
}
n >>>= 1;
}
return count;
}
}
但是第9行写为>>
,循环条件就不可是while(n!=0)
。为简化假设n
只有4位,第1位为符号位,令n=-3
,二进制就是1101
,那么进行n>>=1
后得到的二进制结果为1110
(符号位右移了,但是符号位不会变成0),所以要注意。
参见:Java整数占几个字节,以及负数的二进制表示方法,以及Java的逻辑运算符>>和>>>的区别
2、减一相与法
复杂度
时间 O(N) 空间 O(1)
思路
该方法又叫Brian Kernighan方法。当n
不为0时,n = n & (n - 1);
。因为每次减一如果最右边有1那么消除右边的1,所以消去几次就有几个1。
比如:
- 011,减去1得010,相与得010,消去了最右边的1
- 110,减去1得101,相与得100,消去了最右边的1
代码
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n != 0){
n = n & (n - 1);
count++;
}
return count;
}
}