Arrange Given Numbers to Form The Biggest Number in Java

In this post we’ll see how to write a Java program to arrange given non-negative numbers to form the biggest number. For example if there is an array of numbers {45, 3, 89, 123} then the numbers should be arranged as 89453123 to form the biggest number. If array of integers is {5, 6, 50, 4} then these numbers should be arranged as 65504.

Arrange numbers to form the biggest number solution

If you compare the given numbers as integers to arrange them in decreasing order then for numbers 6 and 50, you will get number as 506 as 50 is greater than 6. So this approach won’t work.

If you convert integer to String and then compare then you may get the numbers in required order. That happens because of the fact that String comparison is lexicographical or alphabetical. In lexicographic order if two strings are compared to determine which one is greater then comparison happens character by character and the first character where these Strings differ determine the order. For example if “Any” and “Amy” are compared to place them in decreasing order then the order is “Any” then “Amy” as n comes after m.
Same way if numbers are compared as String then on comparing “6” and “50” order is 6, 50 as 6 comes after 5.

As an extra precaution you also need to append the first number to the second and second to the first before comparison. For example if you have two numbers A and B then comparison is done for AB and BA (after appending numbers). This is required for strings like “5” and “50” where comparison will place “50” first and then “5”. By appending you won’t have this problem.

Java program to arrange given numbers to form the biggest number

public class ArrangeNumbers {
  public static void main(String[] args) {
    List<Integer> listOfNumbers = Arrays.asList(11, 10, 9, 99, 98);  
    Collections.sort(listOfNumbers, new MyComparator());
    System.out.println("Biggest number is-");
    // Biggest number
    for(Integer i : listOfNumbers){
     System.out.print(i);
    }
  }
}
// Custom comparator for comparison
class MyComparator implements Comparator<Integer>{
  @Override
  public int compare(Integer i, Integer j) {
    // Appending before comparison
    String str1 = i.toString() + j.toString();
    String str2 = j.toString() + i.toString();
    return str2.compareTo(str1);
  }
}

Output

Biggest number is-
999981110

Related Posts

That’s all for the topic Arrange Given Numbers to Form The Biggest Number in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.