leetcode 题目如下 :
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.
思路如下:
这题不难,关键点在于将int转换成二进制,在java中integer中有一个方法toBinaryString(n)可实现,其中那就是题目中的任意整数。
代码如下:
public int HammingWeight(int n) {
int count = 0;
String s = "";
s = Integer.toBinaryString(n);
char temp[] = s.toCharArray();
for(int i = 0 ; i < temp.length ; i++){
if(temp[i] == '1'){
count++;
}
}
return count;
}