- Prepare
- Java
- BigNumber
- Java BigDecimal
- Discussions
Java BigDecimal
Java BigDecimal
+ 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); } }));
}
+ 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.
+ 4 comments Much cleaner in java 8:
String[] x = Arrays.copyOf(s, n); Arrays.sort(x,Collections.reverseOrder(Comparator.comparing(BigDecimal::new))); s = x;
+ 12 comments My Java 8 lambda solution...
//Write your code here Arrays.sort( s, (as,bs) -> {BigDecimal bd = new BigDecimal(bs); return bd.compareTo(new BigDecimal(as));} );
FAILED with...
Exception in thread "main" java.lang.NullPointerException at java.math.BigDecimal.<init>(BigDecimal.java:806) at Solution.lambda`$main$`0(Solution.java:17)
BECAUSE the provided code declared the array too large!
// REPLACE: // String []s=new String[n+2]; // WITH: String []s=new String[n];
With the above fix, it now passes all TC's.
+ 4 comments Sort numbers with bubble sort, and don't lose zeros. Actually we don't change String array.
for (int i = 0; i < s.length-2; i++) { for (int j = 1; j < (n-i); j++) { BigDecimal sj = new BigDecimal(s[j]); BigDecimal sj1 = new BigDecimal(s[j-1]); if(sj.compareTo(sj1) == 1){ String temp = s[j]; s[j] = s[j-1]; s[j-1] = temp; } } }
Sort 379 Discussions, By:
Please Login in order to post a comment