The given Java code is a solution to a problem where we are given an array of strings, each representing a number. The task is to sort these numbers in descending order. The numbers can be very large, hence they are represented as strings.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The solution uses Java's BigDecimal class to handle large numbers. It reads the input numbers as strings and stores them in an array. Then, it sorts the array using a custom comparator that compares the numbers as BigDecimal objects. The comparator is passed to the Arrays.sort method along with the array and the range to sort. The comparator is wrapped with Collections.reverseOrder to sort in descending order. Finally, it prints the sorted numbers.
/**
*
*/
package com.javaaid.hackerrank.solutions.languages.java.bignumber;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
/**
*
*/
public class JavaBigDecimal {
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();
// Write your code here
Arrays.sort(s, 0, n, Collections.reverseOrder(new Comparator() {
public int compare(String s1, String s2) {
BigDecimal b1 = new BigDecimal(s1);
BigDecimal b2 = new BigDecimal(s2);
return b1.compareTo(b2);
}
}));
// Output
for (int i = 0; i < n; i++) {
System.out.println(s[i]);
}
}
}
If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.