要求:
写一个函数,以一个无符号整数为参数,返回其汉明权重。例如,‘11’的二进制表示为'00000000000000000000000000001011', 故函数应当返回3。
汉明权重:指一个字符串中非零字符的个数;对于二进制串,即其中‘1’的个数。
代码如下:
public static int hammingWeight(int n) { String str = Integer.toBinaryString(n); int tmp = 0; char[] ss = str.toCharArray(); for(char s:ss){ if(1 == (s-'0')){ tmp++; } } return tmp; }
看到了另外一个更好的方法,学习了!
http://cwind.iteye.com/blog/2193686#comments