vendredi 27 juillet 2018

Set the digits to the appropriate place

Task: set the digits in the number in their place so in the end you get the highest number. (ex. 58734 - to become 87543).

In this case, I took a 3-digit number,but what if I want a number with many digits (as 58734 in example), do I have to write those if conditions every time, or I can do that some easier and better way?

Here's my code:

    Scanner sc = new Scanner(System.in);

    System.out.print("Enter 3-digit number: ");
    int num = sc.nextInt();
    while (num < 100 || num > 999) {
        System.out.print("Number isn't 3-digit! Enter it again: ");
        num = sc.nextInt();
    }
    int j = num % 10;
    int d = (num / 10);
    d = d % 10;
    int s = num / 100;

    if (j > d) {
        int t = j;
        j = d;
        d = t;
    }
    if (j > s) {
        int t = j;
        j = s;
        s = t;
    }
    if (d > s) {
        int t = d;
        d = s;
        s = t;
    }

    int res = s * 100 + d * 10 + j;
    System.out.println("Result: " + res);

Output:

Enter 3-digit number: 453
Result: 543

Aucun commentaire:

Enregistrer un commentaire