Java BigDecimal

  • + 11 comments

    Java solution - passes 100% of test cases

    From my HackerRank solutions.

    We want to sort in descending order while preserving the contents of each String. A comparator can achieve this for us. We convert to BigDecimal inside our comparator so that the change is not permanent and our String's form for each number is preserved.

    Comparator<String> customComparator = new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            BigDecimal a = new BigDecimal(s1);
            BigDecimal b = new BigDecimal(s2);
            return b.compareTo(a); // descending order
        }
    };
    
    Arrays.sort(s, 0, n, customComparator);
    

    Let me know if you have any questions.