less than 1 minute read

3309. Maximum Possible Number by Binary Concatenation

Solution

class Solution {
    public int maxGoodNumber(int[] nums) {
        // convert int to binary representation 
        // Integer.toBinaryString(int i)
        String[] bins = new String[3];
        
        for(int i = 0; i < nums.length; i++) {
            bins[i] = Integer.toBinaryString(nums[i]);
        }

        Arrays.sort(bins, new Comparator<String>(){
            @Override
            public int compare(String s1, String s2) {
               return (s2 + s1).compareTo(s1 + s2);
            }
        });
        
        // concat the result
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < bins.length; i++) {
            sb.append(bins[i]);
        }
        
        return Integer.parseInt(sb.toString(), 2);
    }
}

Retro

  1. the art of making a comparator, never though can make up comparator in this way