Arrange Given Numbers to Form 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 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 biggest number

Output

That’s all for the topic Arrange Given Numbers to Form 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

  • Java Program to Reverse Each Word in a String
  • Display Armstrong Numbers in Java
  • Cannot Make a Static Reference to The Non-static Method or Field
  • Volatile Keyword in Java
  • Difference Between Runnable And Callable in Java
  • Parquet File Format in Hadoop
  • 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.