-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestion1.java
More file actions
33 lines (29 loc) · 1.01 KB
/
Copy pathQuestion1.java
File metadata and controls
33 lines (29 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package practice4_sort;
import java.util.Arrays;
public class Question1 {
public int[] solution(int[] nums){
int[] answer = new int[nums.length];
int[][] res = new int[nums.length][2];
for(int i = 0; i < nums.length; i++){
int cnt = 0;
int tmp = nums[i];
while(tmp > 0){
cnt += (tmp % 2);
tmp = tmp / 2;
}
res[i][0] = nums[i];
res[i][1] = cnt;
}
Arrays.sort(res, (a, b) -> a[1] == b[1] ? a[0] - b[0] : a[1] - b[1]);
for(int i = 0; i < res.length; i++){
answer[i] = res[i][0];
}
return answer;
}
public static void main(String[] args){
Question1 T = new Question1();
System.out.println(Arrays.toString(T.solution(new int[]{5, 6, 7, 8, 9})));
System.out.println(Arrays.toString(T.solution(new int[]{5, 4, 3, 2, 1})));
System.out.println(Arrays.toString(T.solution(new int[]{12, 5, 7, 23, 45, 21, 17})));
}
}