1. 程式人生 > >用幾個數字任意組合成最大數

用幾個數字任意組合成最大數

例如12,34,56,56,672

組合成最大數為67256563412

原題:

Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.

class Solution {
    public String largestNumber(int[] nums) {
        String[] input = new String[nums.length];
        for(int i = 0;i<nums.length;i++){
            input[i] = String.valueOf(nums[i]);
        }
        Arrays.sort(input, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {//覆寫元素的比較規則
                for(int i = 0; i < o1.length() + o2.length(); i++) {
                    char p1 = o1.charAt(i % o1.length());
                    char p2 = o2.charAt(i % o2.length());
                    if(p1 != p2) return p2 - p1;
                }
                return 0;
            }
        });
        String result = "";
        for(String s : input) {
            result += s;
        }
        int a = 0;
        for(int i = 0;i<result.length();i++){
            
            if(result.charAt(i) == '0'){
               a = i+1;
            }
           if(result.charAt(i) != '0'){
                return result.substring(a,result.length());
            }
        }
        return "0";
    }
}