Wednesday, 22 June 2016

11. [Technical Interview] Given a list of non negative integers, arrange them such that they form the largest number.

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


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.*;

public class HelloWorld{
     public static void main(String []args){
        
        int[] testIntArray = {3, 30};
        System.out.println(largestNumber(testIntArray));
     }
     
     public static String largestNumber(int[] nums)
     {
         String result = "";
         String[] numAsStringsArray = new String[nums.length];
         
         for (int i = 0; i < nums.length; i++)
         {
             numAsStringsArray[i] = Integer.toString(nums[i]);
         }
         
         // The lambda expression must be (str1, str2) -> (str2 + str1).compareTo(str1 + str2)
         // because you are comparing str2 to str1. For example, str1 is 3 and str2 is 30.
         // so we must do (str2 + str1).compareTo(str1 + str2) and not (str1 + str2).compareTo(str2 + str1)
         // because we are comparing str2 to str1, so str2 must come before str1 so it will look like
         // 303 compare to 330, compareTo does natural order in ascending order so we want this way
         Arrays.sort(numAsStringsArray, (str1, str2) -> (str2 + str1).compareTo(str1 + str2));
         
         if (numAsStringsArray[0].equals("0"))
         {
             return "0";
         }
         
         StringBuilder sb = new StringBuilder();
         for (String str : numAsStringsArray)
         {
             sb.append(str);
         }
         
        return sb.toString();   
     }
}

No comments:

Post a Comment

Thank you for not blocking our ads =)

Please consider adding this blog to the whitelist of your ads blocker :)