题目链接:https://leetcode.com/problems/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.
解题思路:
本题考点Bit 操作之逻辑右移。之所以强调逻辑右移>>>,是因为还有个算术右移>>。
1. 算术右移 >>运算符,有符号。右边超出截掉,左边补上符号位
2. 逻辑右移 >>>运算符,无符号,左边补 0
具体步骤:
1. 将 n 与 0x1 做与运算,获得最末一位,若是 1 ,count ++
2. 然后再将 n 逻辑右移 1 位,重复上述操作,直至 n 变为 0.
3. 注意,若用算术右移答案错误。
由于 C / C ++ 没有逻辑右移,故上述方法不可使用,算术右移会将符号位一起参与移位,对于负数,最终会产生 0xFFFFFFFF ,使程序陷入死循环。
另一种思路来自《剑指offer》,采用的是 n & (n - 1) 的方法,将 n 最右的 1 变为 0。把 1 变为 0 多少次说明 n 包含多少个 1。
代码实现:
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 & 0x1) == 1)
count ++;
n = n >>> 1; // 逻辑右移
}
return count;
}
}
600 / 600 test cases passed.
Status: Accepted
Runtime: 2 ms
方法二:
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 - 1) & n;
count ++;
}
return count;
}
}
600 / 600 test cases passed.
Status: Accepted
Runtime: 2 ms