HackerRank Java- BigDecimal




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 .1, and 0.1 is printed as 0.1. If two numbers represent numerically equivalent values , then they must be listed in the same order as they were received as input).



  1. import java.math.BigDecimal;
  2. import java.util.*;
  3. class Solution{
  4. public static void main(String []args){
  5. //Input
  6. Scanner sc= new Scanner(System.in);
  7. int n=sc.nextInt();
  8. String []s=new String[n+2];
  9. for(int i=0;i<n;i++){
  10. s[i]=sc.next();
  11. }
  12. sc.close();
  13. Arrays.sort(s, new Comparator<String>() {
  14. @Override
  15. public int compare(String s1, String s2) {
  16. if (s1 == null || s2 == null) {
  17. return 0;
  18. }
  19. BigDecimal bd1 = new BigDecimal(s1);
  20. BigDecimal bd2 = new BigDecimal(s2);
  21. return bd2.compareTo(bd1);
  22. }
  23. });
  24. //Output
  25. for(int i=0;i<n;i++)
  26. {
  27. System.out.println(s[i]);
  28. }
  29. }
  30. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube