We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Java
  3. BigNumber
  4. Java BigDecimal
  5. Discussions

Java BigDecimal

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • MannB3ast
    6 years ago+ 45 comments

    I loved this problem! Took me forever to figure it out.

    All you need is a comparator. Why? Because you need to keep the strings in the array, but still compare the strings by their BigDecimal values. This is achieved through the comparator.

    Converting the strings to BigDecimals and storing the BigDecimal values will lead to the problem of losing leading zeros on certain string values, so you need the comparator.

    MyCode{

    Arrays.sort(s, Collections.reverseOrder(new Comparator<String>() {
        @Override
        public int compare(String a1, String a2) {
            //convert to big decimal inside comparator
            //so permanent string values are never changed
            //aka you only use the BigDecimal values to 
            //compare the strings!
            BigDecimal a = new BigDecimal(a1);
            BigDecimal b = new BigDecimal(a2);
            return a.compareTo(b);
        }
    }));
    

    }

    172|
    Permalink
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature