Re-arrange the number X
and find the greatest possible number that is less than or equal to Y
. If that is not possible then return -1
.
Also, we should not have leading zeros for the generated output
Example:
X = 2851
Y = 8774
Ans:
8521
Explanation: 8521 is less than or equal to 8774 and it is the largest possible number.
This is the code I tried:
public String process(long X, long Y) {
if(X > Y) return "-1";
char[] arr = (""+X).toCharArray();
Arrays.sort(arr);
String s = new String(arr);
s = new StringBuilder(s).reverse().toString();
long x1 = Long.parseLong(s);
if(x1 <= Y) return "" + x1;
return "=1";
}
My approach is not correct as I am checking for the largest possible number always for the given digits in X. What is the correct approach to solve this program?
Another sample test case that fails with my program is:
Example:
X = 12222
Y = 21111
Expected Ans:
12222