问题:编写了一个函数,它接受一个无符号整数并返回它所拥有的'1‘位数(也称为Hamming重量)。
示例输入:000000000000000000000000001011。
输出:3
解释性:输入二进制字符串0000000000000000000000001011共有三位1‘位。
My方法:公共类解决方案
{
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');
}}
My输入: 1011
My输出:1
预期的正确输出: 3
我不明白为什么这个计算1数的hashmap解决方案不起作用。有人能帮忙吗?
发布于 2020-04-01 18:39:28
试试这个:
int i = 0;
HashMap<Character,Integer> hm = new HashMap<>();
while(i<s.length())
{
if(hm.containsKey(s.charAt(i)))
hm.put(s.charAt(i),hm.get(s.charAt(i))+1);
else
hm.put(s.charAt(i),1);
i+=1;
}
// System.out.println(hm.get('1'));
for (Map.Entry entry : hm.entrySet()) {
System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue());
}输出:

注意事项--需要考虑以下几点的:
if(hm.containsKey(hm.get(i)))替换为if(hm.containsKey(s.charAt(i)))作为键,应引用输入字符串的ith索引字符。hm.put(s.charAt(i),hm.get(i)+1);替换为hm.put(s.charAt(i),hm.get(s.charAt(i))+1);,因为我们首先从hashmap中获取ith索引的值,然后将其递增。https://stackoverflow.com/questions/60967275
复制相似问题