It is necessary to 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 three-digit number, but is there a better, cleaner code, more reasonable? Do I have to write so many if conditions if I have numbers with multiple digits like 58734 in the example?
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