2016-09-08 4 views
0

설정 비트 수를 계산하려고하는데 숫자가 오름차순으로 정렬되어 있습니다. 세트 비트의 카운트까지.다음 코드를 쓸 때 "4 3 10 7"대신 "4 10 7"출력이 나오는 이유는 무엇입니까?

내 입력은 다음과 같습니다

1 
4 
3 4 7 10 

예상 출력은 다음과 같습니다

4 3 10 7 

내 출력은 다음과 같습니다

4 10 7 

표시 할 때 왜 3을 건너 뛰는? I는 A는이 값 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; 
    } 
} 

, 그것 값 3을 판독 되나 해시 맵 가치 및 트리 맵을 통과 한 후에 또 원하는 출력이 표시되지 않는 것으로 나타났다.

+0

가능한 중복 (HTTP : //stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Raedwald

답변

2

당신은 키가 1 비트 수로 보이는 TreeMap의 값으로 4 개 개의 숫자 (4 3 10 7)를 가하고 있습니다 (I 그 static int count(Long n)가 무슨 생각). 310 모두 1 2 비트 (11, 각각 1,010)을 가지고 있으므로 10는 (중복 키를 허용하지 않는 Map 이후)에 Map3 대체하고 3 출력 결코. 기본적으로

, 다음 루프

while(i<n) 
{ 
    Long a=Long.parseLong(ar[i++]); 
    hm.put(count(a),a); 
} 

은 트리 맵에 다음 항목을 삽입 : [? 무엇 디버거이며 그것은 나를 문제를 진단 할 수있는 방법]의

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); 
+0

그래서 어떻게 같은 값을 가진 n 개의 값을 저장할 수 있습니까? –

+0

@MihirMehta'TreeMap >'을 사용할 수 있습니다. – Eran

+0

도움 주셔서 감사합니다. @Eran –