题目:
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.
题意:
给定一个无符号整数,写出一个函数,返回整数中‘1’位的数目。
比如,32位整数‘11’的二进制表示为:00000000000000000000000000001011,因此函数最终得出结果为3
算法分析:
此题比较容易,直接上代码了
代码如下:
public class Solution
{
private int a;
private String m;
private int i;
private int k2;
// you need to treat n as an unsigned value
public int hammingWeight(int n)
{
m=Integer.toBinaryString(n);
k2=0;
for(i=0;i<m.length();i++)
{
if(m.charAt(i)=='1') k2++;
}
return k2;
}
}