我试图计算一个数字中存在的设置位数,并根据设置位的计数按升序排列数字。
我的意见是:
1
4
3 4 7 10
预期输出为:
4 3 10 7
我的输出是:
4 10 7
为什么在显示时跳过3?
package practice;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.TreeMap;
public class MonkAndTasks {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
int k = 0;
while (k < t) {
long n = Long.parseLong(br.readLine());
String str = br.readLine();
String ar[] = str.split(" ");
int i = 0;
HashMap<Integer,Long> hm = new HashMap<Integer,Long>();
while (i < n) {
Long a = Long.parseLong(ar[i++]);
hm.put(count(a), a);
}
TreeMap<Integer,Long> tm = new TreeMap<Integer,Long>(hm);
Collection < Long > c = tm.values();
for (Long e: c) {
System.out.print(e + " ");
}
System.out.println();
}
}
static int count(Long n) {
int c = 0;
while (n > 0) {
n = n & (n - 1);
c++;
}
return c;
}
}
当我打印值a以检查是否读取值3时,事实证明它正在读取值3但是在将值传递给hashmap和treemap之后却没有显示所需的输出。
答案 0 :(得分:2)
您将4个数字(4 3 10 7
)作为值放在TreeMap
中,其中键似乎是1
位的数量(我认为这是static int count(Long n)
一样)。 3
和10
都有2个1
位(分别为11和1010),因此10
会替换3
中的Map
(因为Map
{1}}不允许重复键),永远不会输出3
。
基本上,以下循环
while(i<n)
{
Long a=Long.parseLong(ar[i++]);
hm.put(count(a),a);
}
将以下条目插入TreeMap:
hm.put(1,4);
hm.put(2,3);
hm.put(2,10); // this entry has the same key as the previous entry and therefore
// replaces it
hm.put(3,7);