1

I want to arrange the digits of a number in descending order without using arrays. When I am using String it gives run time error. For example:

Input: 2436
Output: 6432

Here is what I wrote but the problem is the first digit isn't getting printed which is not the expected output.

public static void main (String[] args) throws java.lang.Exception {
    Scanner sc = new Scanner(System.in);
    int num,n,r=0,FinalNo=0;
    System.out.println("Enter any number");
    num=sc.nextInt();
    n=num;
    while(n>0) {
        r=n%10;
        n=n/10;
        FinalNo=(FinalNo*10)+r;
    }
    System.out.println("The number in descending order is "+FinalNo);
}   
Akshit Sinha
  • 58
  • 1
  • 9

2 Answers2

1

Assuming that your number is not greater than Integer.MAX_VALUE you can use Redix Sort algorithm. It works fine with the complexity of O(n). Here, you can find the solution in following code, that doesn't use any array or lists and Strings.

public static void main(String[] args) {
        int number = 45322;
        int sortedNumber = 0;

    /*
     * This loop checks for each digit starting from 9 to 0. 
     * In case of ascending order it should be 0 to 9.
     */
    for (int i = 9; i >= 0; i--) {
        int tmpNumber = number;
        while (tmpNumber > 0) {
            int digit = tmpNumber % 10;
            // Check for the greatest digit in the given number
            if (digit == i) {
                sortedNumber *= 10;
                sortedNumber += digit;
            }
            tmpNumber /= 10;
        }
    }
    System.out.println(sortedNumber); // prints 54322.
}

I think that should work for you.

Procrastinator
  • 2,526
  • 30
  • 27
  • 36
-1

Your example reverses the inputted value, but does not sort it in descending order. You're not allowed to use Strings or arrays (school assignment?), but how about lists?

List<Integer> ints = new LinkedList<>(); // Because ArrayList uses an array internally
while (n > 0) {
    ints.add(n % 10);
    n = n / 10;
}
ints.sort((a, b) -> Integer.compare(b, a)); // Sort in reverse order
System.out.print("The digits in reversed order are: ");
ints.forEach(System.out::print);
System.out.println();
Jeroen Steenbeeke
  • 3,884
  • 5
  • 17
  • 26
  • 1
    I don't want to use list and any other type of shortcut type of thing i want to know about the classic method to solve this. – Akshit Sinha Nov 14 '17 at 09:00
  • I've never had to solve this problem so I don't know the classic solution. However, there was a link posted in comment to your question: https://stackoverflow.com/questions/33971256/how-to-sort-integer-digits-in-ascending-order-without-strings-or-arrays You should be able to adapt the answer given there. – Jeroen Steenbeeke Nov 14 '17 at 09:14