Answers for "largest number solution"

1

largest number

Input: nums = [10,2]
Output: "210"

Input: nums = [3,30,34,5,9]
Output: "9534330"

__________________________________________________________

public String largestNumber(int[] nums) {

    List<String> list = new ArrayList<String>();
    
    for(int i=0;i<nums.length;i++){
        
        list.add(String.valueOf(nums[i]));
    }
    
    Collections.sort(list,new Comparator<String>(){
       
        public int compare(String A,String B){
            String AB = A+B;
            String BA = B+A;
            
            return AB.compareTo(BA) > 0 ? -1 : 1;
        }
        
    });
    
    String res = "";
     for(int i=0;i<list.size();i++){
         res += list.get(i);
    }
    
    if(res.charAt(0) == '0')
        return "0";
    
    return res;
}
Posted by: Guest on August-06-2021

Browse Popular Code Answers by Language