×

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with one another once you provide the array's numbers as input. It will then draw a conclusion.

The topic is the most well-known challenge that major IT organisations (including Apple, Google, Amazon, and Microsoft) typically ask candidates about during the coding section of the interview. We'll write Java programmes (using various logics) in this section to extract the greatest number from an array.

For instance, enter 10, 68, 75, 7, 21, and 12.

Produced by: 77568211210

The biggest number that may be generated from the above-mentioned array is 77568211210. It's crucial to remember that it doesn't matter what sequence we combine the integers together in.

The Problem's Solution

The intended result cannot be achieved by simply sorting the arrays in decreasing order and taking that sorted order to be the desired result since the integer may not be the greatest number.

The pairwise comparisons (XY and YX) will be compared first, and the bigger number will be displayed first in the sorted order. Next, we will develop a unique comparator method for the sorting process. Notably, comparing Y and X together is not necessary in this case.

BN.java

//importing the required packages
import java.util.Arrays;  
import java.util.Collections;  
import java.util.List;  
import java.util.stream.Collectors;  
public class BN 
{  
// function that builds the largest number
public static String findBN(List<Integer> nums)  
{  
//sort using a custom function object  
Collections.sort(nums, (a, b) -> (String.valueOf(b) + a).compareTo(String.valueOf(a) + b));  
return nums.stream().map(Object::toString).collect(Collectors.joining(""));  
}  
//driver code  
public static void main(String args[])  
{  
List<Integer> numz = Arrays.asList(7, 55,86,5,18, 34, 54, 0, 90);  
String BN = findBN(numz);  
System.out.println("The largest number is: " + BN);  
}  
}  

Output:

 The largest number present is: 908775854342160

The aforementioned program's complexity is O (nlogn). where the input size (n) is.

Here is another justification for the same.

The following Java application creates a string out of each entry in an array. It will be beneficial to convert numbers into string if indeed the array includes more numbers since when we add up each number, we get a big amount. The array was then sorted (in descending order). When an array is sorted in descending order, there may be an issue if a group of numbers have the same starting digits.

Consider the array 3, 30, 34, 5, 9 as an illustration.

9534303 is created as the greatest number when the aforementioned array is sorted in descending order. However, that is not the right response. You may get the right response by flipping the numbers 33 and 3030.

As a result, when shorting, evaluate (for each pair - wise comparisons) the result of appending the pair in the two different orders. The intended outcome is obtained as the greatest integer once the array has been sorted.

There could be a circumstance when an array is made up entirely of zeros. If 00 is the largest number in this situation, then return 00. Otherwise, return the greatest value from the sorted array.

Let's put the aforementioned reasoning into a Java application.

LargerNumberComparator.java

import java.util.*;  
public class LargestNumber {  
    private class LargerNumberComparator implements Comparator<String> {  
        @Override  
        public int compare(String a, String b) {  
            S o1 = x + y;  
            S o2 = y + x;  
            return o2.compareTo(o1);  
        }  
    }  
    // function that determines the array's biggest number
    public String BN(int[] num) {  
        //getting up the input integers as in strings  
        String[] asStrs = new String[num.length];  
        for (int i = 0; i < num.length; i++) {  
            aStrs[i] = String.valueOf(num[i]);  
        }  
        Arrays.sort(aStrs, new BNComparator());  
        if (aStrs[0].equals("0")) {  
            return "0";  
        }    
        String BNS = new String();  
        for (String numAsStr : asStrs) {  
            BNS += numAsStr;  
        }  
        return BNS;  
    }  
    public static void main(String s[]) {  
        int aa[] = { 7, 22,89,36,14, 54, 0, 90 };  
        BN ln = new BN();  
        String s = ln.lBN(aa);  
        System.out.println("The constructed largest number in array is:" +s);  
    }  
}  

Output:

The constructed largest number in array is:908784864342160

Because we used more space to store the integers, the time complexity for the aforementioned method is O(nlogn) as well as the space complexity is O(n).


Related Topics

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

Array and String with Examples in Java

Array in Java: An array in Java is a group of variables with similar types that have a common name. The arrays used in Java differ from those used in C/C++. Key...

6 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Convert Char array to string in java

A collection of characters is referred to as a string. A character array differs from a string in that the string is canceled by the special character "\0." A string...

4 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

Difference between String Tokenizer and split Method in Java

Introduction Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences String...

7 minutes read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.