Java BigDecimal

  • + 2 comments

    I really can't understand why test case 0 is wrong with the code i wrote. It seems that it keeps switching 0.12 with .12 and I don't know why. I would really appreciate if someone could explain it to me.

    import java.math.BigDecimal; import java.util.*; class Solution{

    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=1; i<n; i++){
        for(int j=0; j<n; j++){
        BigDecimal bd1 = new BigDecimal(s[i]);
        BigDecimal bd2= new BigDecimal(s[j]);
        int smaller=bd1.compareTo(bd2);
        String tempS;
        if(smaller==0)
            continue;
        else if(smaller==1)
        {
            tempS=s[i];
            s[i]=s[j];
            s[j]=tempS;
    
        }
    
      }
      }
        //Output
        for(int i=0;i<n;i++)
        {
            System.out.println(s[i]);
        }
    }
    

    }

    • + 0 comments

      Check your output: your result puts .12 before 0.12, but it's wrong since it's required that:

      If two numbers represent numerically equivalent values (e.g., ), then they must be listed in the same order as they were received as input).

      So, the sorting algorithm you used is not stable. I tried to fix your code, using the Bubble Sort:

      String tempS;
      for (int i=0; i<n-1; i++) {
          for (int j=0; j<n-i-1; j++) {
              BigDecimal bd1 = new BigDecimal(s[j]);
              BigDecimal bd2 = new BigDecimal(s[j+1]);
              if (bd1.compareTo(bd2)<0) {
                  tempS = s[j];
                  s[j] = s[j+1];
                  s[j+1] = tempS;
              }
          }
      }