Search code examples
javapermutation

Find the maximum integer, that can be obtained by permutation of numbers of an arbitrary three-digit positive integer n (100<=n<=999)


Find the maximum integer, that can be obtained by permutation of numbers of an arbitrary three-digit positive integer n (100<=n<=999).

public static int maxNum(int n) {
int j , k ,l, result;
String  q, z, y ,w;

    do {
        j = n % 10;
        k = n % 100/ 10;
        l = n % 1000 /100;

        q =Integer.toString(k);
        z =Integer.toString(j);
        y =Integer.toString(l);
        w= (q+z+y);
        result =Integer.parseInt(w);

        break;
    } while (n >=100 && n<=999);

    return result;
}


``` input 

165

output 

651    

input 123 

output 
321

Solution

  • You need to order the digits in descending order and then build up the 3 digit value accordingly.

    - 152 - 1, 5, 2
    - in ascending order is 5, 2, 1
    - ( 10 * 5) + 2) * 10) + 1 = 521
    

    Here is one way to do it with streams.

    Random r = new Random();
    
    • generate a value between 100 and 999 inclusive
    • convert to a String and split the digit characters
    • sort in descending order
    • convert each integer to a numeric digit
    • and use reduce to get the largest number
    for (int i = 0; i < 10; i++) {
         int value = r.nextInt(100, 1000);
         int max = Arrays.stream(Integer.toString(value).split(""))
                 .sorted(Comparator.reverseOrder())
                 .mapToInt(Integer::parseInt)
                 .reduce(0, (a, b) -> a * 10 + b);
         System.out.println(value + " -> " + max);
    }
    

    prints something like the following:

    105 -> 510
    694 -> 964
    983 -> 983
    432 -> 432
    792 -> 972
    868 -> 886
    979 -> 997
    839 -> 983
    803 -> 830
    911 -> 911
    

    You can also do it without sorting and using just a single while loop.

    • the while loop simply replaces the sorting by ordering the 3 digits in decreasing order.
    • then max1, max2, and max3 are combined as previously explained.
    for (int i = 0; i < 10; i++) {
         int value = r.nextInt(100,1000);
         int max1 = 0,max2 = 0,max3 = 0;
         int temp = value; // save for later printing.
         while (value > 0) {
             int d = value % 10; // get last digit of value
          
             if (max1 < d) {
                 max3 = max2;
                 max2 = max1;
                 max1 = d;
             }
             else if (max2 < d) {
                 max3 = max2;
                 max2 = d;
             }
             else if (max3 < d) {
                 max3 = d;
             }
             value /= 10;  // expose next digit
         }
         
         int max = (((max1*10)+max2)*10)+max3;
         System.out.println(temp + " -> " + max);     
     }