LeetCode[191] Number of 1 Bits
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.
依次移位
复杂度
O(N), O(1), N = number of bits in the interger
思路
依次移动位数进行计算。
The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
So when the first bit is 1, if use >>, 1 will always be there, then the loop will never end.
代码
public int hammingWeight(int n) {
int cnt = 0;
while(n != 0) {
if((n & 1) == 1) {
cnt ++;
}
// must use unsigned operation
n = n >>> 1;
}
return cnt;
}
利用性质 n & (n - 1)
复杂度
O(N), O(1), N = number of 1 bits in the number
思路
consider n & (n - 1) always eliminates the least significant 1.
代码
public int hammingWeight(int n) {
int cnt = 0;
// loop times = number of 1's in the n
while(n != 0) {
n = n & (n - 1);
cnt ++;
}
return cnt;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。