32. Arrange the array to the smallest number

Topic description

        Input an array of positive integers, concatenate all the numbers in the array into a number, and print the smallest one of all the numbers that can be concatenated. For example, if the array {3, 32, 321} is input, the smallest number that can be arranged by these three numbers is 321323;

Problem solving ideas

         1. Convert an array of positive integers to an array of Strings;

         2. Sort String according to the following rules: after converting a and b into strings, if ab < ba a is sorted first, such as 2 21 because 212 < 221, so the sorting is 21 2;

     public String PrintMinNumber(int[] numbers) {
        if (numbers == null || numbers.length == 0) {
            return "";
        }

        //Convert integer array to String array
        String[] arrays = new String[numbers.length];
        for (int i = 0; i < numbers.length; i++) {
            arrays[i] = String.valueOf(numbers[i]);
        }

        // sort it
        Arrays.sort(arrays, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                String c1 = s1 + s2;
                String c2 = s2 + s1;
                return c1.compareTo(c2);
            }
        });

        //Calculation results
        StringBuffer result = new StringBuffer();
        for (String s : arrays) {
            result.append(s);
        }

        return result.toString();
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325868462&siteId=291194637