#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
template <class c>
struct rge {
  c b, e;
};
template <class c>
rge<c> range(c i, c j) {
  return rge<c>{i, j};
}
template <class c>
auto dud(c* x) -> decltype(cerr << *x, 0);
template <class c>
char dud(...);
struct debug {
  template <class c>
  debug& operator<<(const c&) {
    return *this;
  }
};
string a, b;
string calc(long long i, map<long long, long long> cnt) {
  if (i == (long long)(b.size())) {
    return "";
  }
  if (cnt[b[i] - '0']) {
    cnt[b[i] - '0'] -= 1;
    string ans = calc(i + 1, cnt);
    if (ans != "-1") {
      ans.insert(ans.begin(), b[i]);
      return ans;
    }
    cnt[b[i] - '0'] += 1;
  }
  for (long long j = b[i] - '0' - 1; j >= 0; j--) {
    if (cnt[j]) {
      string ans = "";
      ans += (j + '0');
      cnt[j] -= 1;
      for (long long k = 9; k >= 0; k--) {
        while (cnt[k]--) {
          ans += (k + '0');
        }
      }
      return ans;
    }
  }
  return "-1";
}
void solve() {
  cin >> a >> b;
  if ((long long)(a.size()) < (long long)(b.size())) {
    sort(a.begin(), a.end());
    reverse(a.begin(), a.end());
    cout << a << '\n';
    return;
  }
  map<long long, long long> cnt;
  for (char c : a) {
    cnt[c - '0'] += 1;
  }
  cout << calc(0, cnt) << '\n';
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  while (t--) {
    solve();
  }
  return 0;
}
