Skip to content

Instantly share code, notes, and snippets.

@rohangho
Created June 28, 2019 16:23
Show Gist options
  • Save rohangho/bc4ad318e35f2cc7284883a2df1b571a to your computer and use it in GitHub Desktop.
Save rohangho/bc4ad318e35f2cc7284883a2df1b571a to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
String bToString = Integer.toString(b);
String aToString = Integer.toString(a);
int firstDigit = Character.getNumericValue(bToString.charAt(0));
int k = a;
ArrayList<Integer> listDigits = new ArrayList<Integer>();
ArrayList<Integer> listOdDigitBuffer = new ArrayList<Integer>();
while (k > 0) {
int lastDigit = k % 10;
listDigits.add(lastDigit);
listOdDigitBuffer.add(lastDigit);
k = k / 10;
}
Collections.sort(listDigits);
String s;
int[] duplicatearray = new int[listDigits.size()];
for (int i = 0; i < listDigits.size(); i++)
duplicatearray[i] = listDigits.get(i);
int m = 0;
while (true) {
listDigits = new ArrayList<Integer>();
for (int f = 0; f < duplicatearray.length; f++)
listDigits.add(duplicatearray[f]);
s = null;
for (int i = 0; i < listDigits.size(); i++) {
if (firstDigit <= listDigits.get(i) && m == 0) {
s = Integer.toString(listDigits.get(i));
listDigits.remove(i);
break;
} else if (firstDigit < listDigits.get(i) && m == 1) {
s = Integer.toString(listDigits.get(i));
listDigits.remove(i);
break;
}
}
if (s == null) {
System.out.println(-1);
break;
}
if (Integer.parseInt(s) == firstDigit) {
for (int j = 1; j < bToString.length(); j++) {
for (int x = 0; x < listDigits.size(); x++) {
if (Character.getNumericValue(bToString.charAt(j)) <= listDigits.get(x)) {
s = s + Integer.toString(listDigits.get(x));
listDigits.remove(x);
break;
}
}
}
} else {
for (int j = 1; j < bToString.length(); j++) {
for (int x = 0; x < listDigits.size(); x++) {
s = s + Integer.toString(listDigits.get(x));
listDigits.remove(x);
break;
}
}
}
if (s != null) {
if (Integer.parseInt(s) > b) {
System.out.println(s);
break;
}
}
if (m == 1) {
System.out.println(-1);
break;
}
m++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment