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.
思路:
java有一个Integer,toBinaryString的函数可以利用。
如果从二进制特点来看:
n为奇数(n的二进制表示的末位为1):
n: xxxxxxxx1
n-1: xxxxxxxx0
n&(n1-): xxxxxxxx0
相当于去掉最右边的一个1。
n为偶数且不等于0(n的二进制表示的末位为0):
n: xxxxx1000
n-1: xxxxx0111
n&(n1-): xxxxx0000
也是相当于去掉最右边的一个1。
解法1:
public class Solution {
public static int hammingWeight(int n) {
int count = 0;
String str = Integer.toBinaryString(n);
for(int i = 0;i < str.length();i++){
if(str.charAt(i) == '1'){
count++;
}
}
return count;
}
}
解法2:
public class Solution {
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n = n & (n - 1);
count++;
}
return count;
}
}