|
Maximum number from the digits of a number
Find the maximum possible number from the digits of a given number.
|
package com.bethecoder.tutorials.coding.examples;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MaxNumberTest {
public static void main (String [] args) {
int num = 1729;
System.out.println("Max number from digits of " + num + " is " +getMaxNumber (num) );
num = 412356879;
System.out.println("Max number from digits of " + num + " is " +getMaxNumber (num) );
}
private static int getMaxNumber(int num) {
List<Integer> digits = new ArrayList<Integer>();
int digit = 0;
num = Math.abs(num);
while (num > 0) {
digit = num % 10;
num = num/10;
digits.add(digit);
}
Collections.sort(digits);
int sum = 0;
for (int i = digits.size()-1 ; i >= 0 ; i --) {
sum = (sum * 10) + digits.get(i);
}
return sum;
}
}
|
| |
It gives the following output,
Max number from digits of 1729 is 9721
Max number from digits of 412356879 is 987654321
|
|