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.
Credits: Special thanks to @ts for adding this problem and creating all test cases.
先科普一个按位与的问题:
System.out.println("---" + (1100010011 & 1));这个输出是 1
System.out.println("---" + (1100010010 & 1));这个输出是 0
System.out.println("---" + (1100010011 & 11));这个输出是 11
以此类推。
我写的这个很好理解。每次按照无符号数右移一位然后赋值给自己,最后一位为1,res就会加一,为0就加零,最后返回即可。
public int hammingWeight(int n) { int res = 0; while (n != 0) { res += n & 1; n >>>= 1; } return res; }这个是别人的答案,也是Accept的,但是我没看太懂。
public int hammingWeight2(int n) { if (n == 0) return 0; int count = 1; while ((n & (n - 1)) != 0) { n &= n - 1; count++; } return count; }给出官方做法。
Approach #1 (Loop and Flip) [Accepted]
public int hammingWeight(int n) { int bits = 0; int mask = 1; for (int i = 0; i < 32; i++) { if ((n & mask) != 0) { bits++; } mask <<= 1; } return bits; }Approach #2 (Bit Manipulation Trick) [Accepted]
public int hammingWeight(int n) { int sum = 0; while (n != 0) { sum++; n &= (n - 1); } return sum; }LeetCode官方讨论区
