How can I manipulate an array to make the largest number?

前端 未结 16 2135
暖寄归人
暖寄归人 2021-01-30 02:47

Say you have an array of positive integers, manipulate them so that the concatenation of the integers of the resultant array is the largest number possible. Ex: {9,1,95,17,5}, r

16条回答
  •  暖寄归人
    2021-01-30 03:02

    Here is the simple implementation in java without using comparator

    import java.util.List;

    import java.util.ArrayList;

    import java.util.*;

    import java.lang.Math;

    public class LargestNumber{

    public static void main(String args[]){
        ArrayList al = new ArrayList(); 
        al.add(872);
        al.add(625);
        al.add(92);
        al.add(8);
        al.add(71);
    
        Find find = new Find();
        find.duplicate(al);
        }
    

    }

    class Find{

    public void duplicate(ArrayList al){
        String numL ="";
        int size = al.size();
        Collections.sort(al,Collections.reverseOrder());
        ArrayList arrL = new ArrayList();
        for(int i = 0; i < size; i++){
            for(int j = 0; j < size - 1; j++){
                if((compare(al.get(j), al.get(j+1))) == 1){
                    Collections.swap(al,j,j+1);
                }
            }
        }
    
        for(int i = 0; i < size; i++){
            numL = numL + al.get(i);
        }
        System.out.println(numL);
    
    }
    
    public static int compare(int x, int y){
    
        String xStr = String.valueOf(x);
        String yStr = String.valueOf(y);
    
        int a = Integer.parseInt(xStr+yStr);
        int b = Integer.parseInt(yStr+xStr);
    
        return (a>b)? 0:1;
    }
    

    }

    Output 92887271625

提交回复
热议问题