×

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

Java Continue Keyword

The java keyword ‘continues’ has also been called as java continue statement.The main concepts of the java continue statement or keyword is used in the controlling of the loop structure.Java...

3 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Dictionary in Java

Dictionary in Java The Dictionary class represents a key-value relation which maps keys to values. In Dictionary class, every key and every value is an object. It is an abstract class associated with...

2 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

All the important string methods in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.