#include <bits/stdc++.h>
using namespace std;
long long a, b;
string as, bs;
int len(long long x) { return to_string(x).length(); }
int gn(char dg) { return (int)(dg - '0'); }
pair<string, bool> fmax(vector<int> dc, int p, bool smad) {
  string res = "";
  if (smad) {
    for (int i = 9; i >= 0; --i) {
      for (int j = 0; j < dc[i]; ++j) {
        res += to_string(i);
      }
    }
    return {res, true};
  }
  int dib = gn(bs[p]);
  if (dc[dib] > 0) {
    dc[dib]--;
    if (p < as.length() - 1) {
      auto nres = fmax(dc, p + 1, false);
      if (nres.second) {
        res += bs[p];
        res += nres.first;
        return {res, true};
      }
    } else {
      res += bs[p];
      return {res, true};
    }
    dc[dib]++;
  }
  for (int i = dib - 1; i >= 0; --i) {
    if (dc[i] > 0) {
      dc[i]--;
      auto nres = fmax(dc, p + 1, true);
      res += to_string(i);
      res += nres.first;
      return {res, true};
    }
  }
  return {res, false};
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin >> a >> b;
  as = to_string(a);
  bs = to_string(b);
  if (len(b) > len(a)) {
    sort(as.begin(), as.end());
    reverse(as.begin(), as.end());
    cout << as << "\n";
    return 0;
  }
  if (len(b) < len(a)) {
    cout << "-1\n";
    return 0;
  }
  vector<int> v;
  for (int i = 0; i <= 9; ++i) {
    int cc = 0;
    for (int j = 0; j < as.length(); ++j) {
      if (gn(as[j]) == i) {
        cc++;
      }
    }
    v.push_back(cc);
  }
  auto res = fmax(v, 0, false);
  if (!res.second) {
    cout << "-1\n";
  } else {
    cout << res.first << "\n";
  }
  return 0;
}
