Java's BigDecimal class can handle arbitrary-precision signed decimal numbers. Let's test your knowledge of them!
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 (e.g., .1=0.1), then they must be listed in the same order as they were received as input).
Complete the code in the unlocked section of the editor below. You must rearrange array 's elements according to the instructions above.
Sample Input
9
-100
50
0
56.6
90
0.12
.12
02.34
000.000
Sample Output
90
56.6
50
02.34
0.12
.12
0
000.000
-100
Java Code:
import java.util.Scanner;
import java.math.BigDecimal;
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();
for (int i = 0; i < n - 1; i++) {
boolean swapped = false;
for (int j = 0; j < n - 1 - i; j++) {
BigDecimal bdNum1 = new BigDecimal(s[j]);
BigDecimal bdNum2 = new BigDecimal(s[j + 1]);
if (bdNum1.compareTo(bdNum2) == -1) {
String smallerNum = s[j];
s[j] = s[j + 1];
s[j + 1] = smallerNum;
swapped = true;
}
}
if (!swapped) {
break;
}
}
//Output
for(int i=0;i<n;i++)
{
System.out.println(s[i]);
}
}
}
No comments:
Post a Comment