Java BigDecimal

Sort by

recency

|

493 Discussions

|

  • + 0 comments

    Important hint, the print is already in the lower end of the code. Hope no one wastes so much time like me because I wasn't realizing how my list was duplicating

  • + 0 comments
    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();
    
            //Write your code here
    
    for(int i=0;i<n;i++)
    {
        //inserting string values to bigdecimal
        BigDecimal First=new BigDecimal(s[i]);
        int index=i;
        for(int j=i+1;j<n;j++)
        {
            //second BigDecimal to compare the first Bigdecimal
            BigDecimal Second=new BigDecimal(s[j]);
    
            //comparing if First element is greater that second element
            //if the First element is greater than Second element than compareTo() returns 1
    
            if(Second.compareTo(First)==1){
                First=Second;
                index=j;
            }
        }
    
        //temporary variable to store s[i] value
    
            String temp=s[i];
            s[i]=s[index];
            s[index]=temp;
    }
          
            //Output
            for(int i=0;i<n;i++)
            {
                System.out.println(s[i]);
            }
        }
    
    }
    
  • + 1 comment

    in the Java8 version they (I don't know how intentionally) added two empty cells in the array:

    String []s=new String[n+2];
    

    You must remove them ... or you'll get an NPE in the new BigDecimal(s[i])

  • + 0 comments
        Arrays.sort(s, 0, n, (s1, s2) -> {
            return new BigDecimal(s2).compareTo(new BigDecimal(s1));});
    
  • + 0 comments

    import java.io.; import java.util.; import java.math.BigDecimal;

    public class Solution {

    public static void main(String[] args) {
    
        Scanner sc= new Scanner(System.in);
    int n=sc.nextInt();
    // System.out.println(n);
    String[] s=new String[n];
    for(int i=0;i<n;i++){
        s[i]=sc.next();
    }
    sc.close();
    Arrays.sort(s, new Comparator<String>() {
    @Override
    public int compare(String a, String b) {
        BigDecimal decimal1 = new BigDecimal(a);
        BigDecimal decimal2 = new BigDecimal(b);
        return +decimal2.compareTo(decimal1);
        // return decimal2.compareTo(decimal1); for Asscending order write -
    }
    

    });

    for(int i=0;i<n;i++)
    {
        System.out.println(s[i]);
    }
        }
    }