问题:编写一个函数,该函数采用无符号整数并返回其具有的“ 1”位数(也称为汉明权重)。
[示例输入: 00000000000000000000000000001011。输出: 3说明:输入的二进制字符串00000000000000000000000000001011总共有三个“ 1”位。
我的方法:公共类解决方案
{
public int hammingWeight(int n)
{
int i=0;
String s = Integer.toString(n);
HashMap<Character,Integer> hm = new HashMap<>();
while(i<s.length())
{
if(hm.containsKey(hm.get(i)))
hm.put(s.charAt(i),hm.get(i)+1);
else
hm.put(s.charAt(i),1);
i+=1;
}
return hm.get('1');
}
}
我的输入: 1011
我的输出: 1
预期正确的输出: 3
我不明白为什么这种用于计数1的哈希图解决方案不起作用。有人可以帮忙吗?
尝试一下:
private static void code(String s) {
HashMap<Character,Integer> hm = new HashMap<>();
char[] str = s.toCharArray();
for(char c: str) {
if(hm.containsKey(c)) {
hm.put(c, hm.get(c) + 1);
}
else
hm.put(c, 1);
}
for (Map.Entry entry : hm.entrySet()) {
System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue());
}
}
输出: