Java BigDecimal in Java : Hacker Rank Solution : Digit Wood

Java
,

Java’s BigDecimal class can handle arbitrary-precision signed decimal numbers. Let’s test your knowledge of them!

Given an array,s , of n real number strings, sort them in descending order — but wait, there’s more! Each number must be printed in the exact same format as it was read from stdin, meaning that .1 is printed as 0.1, and  is printed as . If two numbers represent numerically equivalent values (e.g.,.1=0.1 ), then they must be listed in the same order as they were received as input).

Complete the code in the unlocked section of the editor below. You must rearrange array ‘s elements according to the instructions above.

Output Format

Locked stub code in the editor will print the contents of array  to stdout. You are only responsible for reordering the array’s elements.

Sample Input

Sample Output

SOLUTION : –

import java.math.BigDecimal;
import java.util.*;
class Solution{
    public static void main(String []args){
        //Input
        Scanner sc= new Scanner(System.in);
        int n=sc.nextInt();
        String []s=new String[n+2];
        for(int i=0;i<n;i++){
            s[i]=sc.next();
        }
        sc.close();

      Arrays.sort(s, 0, n, (a, b) -> {
        BigDecimal aBigDecimal = new BigDecimal(a);
        BigDecimal bBigDecimal = new BigDecimal(b);
        return bBigDecimal.compareTo(aBigDecimal);
    });

        //Output
        for(int i=0;i<n;i++)
        {
            System.out.println(s[i]);
        }
    }
}

FOLLOW FOR MORE QUESTIONS AND SOLUTIONS | DIGIT WOOD

Leave a Reply

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