I am trying to count the number of set bits are present in a number and arranging the numbers in the ascending order according to the count of the set bits.
My input is :
1
4
3 4 7 10
Expected Output is:
4 3 10 7
My output is:
4 10 7
Why is it skipping 3 when displaying?
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;
}
}
When I print the value a to check whether a reads the value 3 or not, it turns out that it is reading the value 3 but after passing value to hashmap and treemap yet the desired output is not displayed.