You are given two positive integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0.

It is allowed to leave a as it is.


-----Input-----

The first line contains integer a (1 ≤ a ≤ 10^18). The second line contains integer b (1 ≤ b ≤ 10^18). Numbers don't have leading zeroes. It is guaranteed that answer exists.


-----Output-----

Print the maximum possible number that is a permutation of digits of a and is not greater than b. The answer can't have any leading zeroes. It is guaranteed that the answer exists.

The number in the output should have exactly the same length as number a. It should be a permutation of digits of a.


-----Examples-----
Input
123
222

Output
213

Input
3921
10000

Output
9321

Input
4940
5000

Output
4940

Difficulty: MEDIUM_HARD
Tags: Dynamic programming

Greedy algorithms
Skill types: Dynamic programming

Greedy algorithms

Starter code:

Solutions:
fact_ = [1] * 50

def fact(n):
	return fact_[n]

def get_perm(n, k):
	if k > fact(n):
		exit(123)
	if n == 1:
		return [1]
	k -= 1
	res = []
	not_used = [i for i in range(1, n + 1)]
	size = fact(n - 1)
	for i in range(n):
		cnt = k // size
		res.append(not_used[cnt])
		not_used.pop(cnt)
		k %= size
		if i != n - 1:
			size //= n - 1 - i
	return res[:]

def num_by_perm(x):
	nonlocal n, a
	v = get_perm(n, x)
	res = []
	for i in range(n):
		res.append(a[v[i] - 1])
	return int(''.join(res))

def check(x):
	nonlocal n, a, b
	v = num_by_perm(x)
	if v > b:
		return False
	else:
		return True
for i in range(1, 20):
	fact_[i] = fact_[i - 1] * i
a = list(input())
b = int(input())
n = len(a)
a.sort()
l = 1
r = fact(n) + 1
while r - l > 1:
	m = l + (r - l) // 2
	if check(m):
		l = m
	else:
		r = m
print(num_by_perm(l))


a = int(input())
b = int(input())
x = [0] * 10
while a:
	x[a % 10] += 1
	a = a // 10
ans = 0
for i in range(9, -1, -1):
	for j in range(x[i]):
		ans = ans * 10 + i
if ans <= b:
	print(ans)
else:
	ans = 0
	for j in str(b):
		c = int(j)
		while c >= 0 and (not x[c]):
			c -= 1
		if c < 0:
			while True:
				x[ans % 10] += 1
				d = ans % 10
				ans = ans // 10
				flag = 0
				for b in range(d - 1, -1, -1):
					if x[b]:
						ans = ans * 10 + b
						x[b] -= 1
						flag = 1
						break
				if flag:
					break
			break
		else:
			x[c] -= 1
			ans = ans * 10 + c
			if c < int(j):
				break
	for j in range(9, -1, -1):
		for i in range(x[j]):
			ans = ans * 10 + j
	print(ans)


from bisect import *
a = sorted(input())
b = input()
if len(a) < len(b):
	print(''.join(reversed(a)))
	return
res = ''
lower = False
for i in range(len(b)):
	for j in range(len(a) - 1, -1, -1):
		bb = b[i + 1:]
		aa = a[:j] + a[j + 1:]
		if a[j] < b[i] or (a[j] == b[i] and ''.join(aa) <= bb):
			res += a[j]
			a = aa
			break
	if res[-1] < b[i]:
		break
print(res + ''.join(reversed(a)))


a = input()
b = input()
if len(a) < len(b):
	q = list(a)
	q.sort(reverse=True)
	print(''.join(q))
else:
	ans = ''
	flag = 0
	while flag == 0 and len(b) != 0:
		cur = 0
		while cur < len(a) and a[cur] != b[0]:
			cur += 1
		if cur < len(a):
			ans = ans + a[cur]
			a = a[:cur] + a[cur + 1:]
			b = b[1:]
		else:
			flag = 1
	if len(b) == 0:
		print(ans)
	else:
		ma = -1
		p = -1
		for i in range(len(a)):
			if int(a[i]) > ma and int(a[i]) < int(b[0]):
				ma = int(a[i])
				p = i
		if ma != -1:
			l = a[p]
			a = a[:p] + a[p + 1:]
			q = list(a)
			q.sort(reverse=True)
			print(ans + l + ''.join(q))
		else:
			flag = 0
			while flag == 0:
				ma = -1
				p = -1
				for i in range(len(a)):
					if int(a[i]) > ma and int(a[i]) < int(ans[-1]):
						ma = int(a[i])
						p = i
				if ma != -1:
					a = a + ans[-1]
					ans = ans[:-1] + a[p]
					a = a[:p] + a[p + 1:]
					q = list(a)
					q.sort(reverse=True)
					print(ans + ''.join(q))
					flag = 1
				else:
					a = a + ans[-1]
					ans = ans[:-1]


from functools import reduce
from fractions import gcd
import copy
from pip._vendor.distlib.compat import raw_input
import math
from decimal import *
getcontext().prec = 6
a = raw_input()
b = raw_input()
x = [None] * len(a)
y = [None] * len(b)
for i in range(len(a)):
	x[i] = int(a[i])
for i in range(len(b)):
	y[i] = int(b[i])

def zjisti(x, y):
	x.sort(reverse=True)
	c = copy.deepcopy(x)
	vysl1 = []
	if len(x) < len(y):
		v = ''
		for i in range(len(x)):
			v += str(x[i])
		return v
	if y[0] in x:
		x.remove(y[0])
		vysl1.append(y[0])
		jup = 0
		for i in range(len(y) - 1):
			if y[i + 1] < x[len(x) - i - 1]:
				jup = -1
				break
			elif y[i + 1] > x[len(x) - i - 1]:
				break
		if jup == 0:
			o = y[0]
			y.remove(y[0])
			if len(x) > 0:
				return str(o) + zjisti(x, y)
			else:
				return str(o)
	q = y[0]
	for j in range(len(c)):
		if c[j] < q:
			s = c[j]
			break
	v = str(s)
	c.remove(s)
	for i in range(len(c)):
		v += str(c[i])
	return v
print(zjisti(x, y))


a = list(input())
b = int(input())
pre = ''
a.sort()
a.reverse()
while len(a) > 0:
	for i in range(0, len(a)):
		numb = pre + a[i] + ''.join(sorted(a[:i] + a[i + 1:]))
		if int(numb) <= b:
			pre += a[i]
			a = a[:i] + a[i + 1:]
			break
print(pre)


from collections import defaultdict
a = input()
b = input()

def form(a_digits):
	answer = []
	for i in sorted(a_digits, reverse=True):
		answer.append(i * a_digits[i])
	return ''.join(answer)

def main():
	if len(b) > len(a):
		return ''.join(sorted(list(a), reverse=True))
	else:
		a_digits = defaultdict(int)
		for x in a:
			a_digits[x] += 1
		r = 0
		for x in b:
			if a_digits[x] > 0:
				a_digits[x] -= 1
				r += 1
			else:
				for i in range(r, -1, -1):
					for j in range(int(b[i]) - 1, -1, -1):
						if a_digits[str(j)] > 0:
							a_digits[str(j)] -= 1
							return b[:i] + str(j) + form(a_digits)
					a_digits[b[i - 1]] += 1
		return b
print(main())


def x(a, b):
	a.sort()
	l = len(a)
	if len(a) < len(b):
		return ''.join(sorted(a, reverse=True))
	elif l > len(b):
		return '0' + x(a[1:], b)
	else:
		f = True
		if l == 0:
			return ''
		for i in range(l):
			if a[i] > b[i]:
				f = False
			elif a[i] < b[i]:
				break
		if not f:
			return -1
		a = list(a)
		a.sort(reverse=True)
		o = ''
		if b[0] in a:
			f = a.index(b[0])
			t = x(a[:f] + a[f + 1:], b[1:])
			f2 = -1
			if t == -1:
				m = '9'
				f2 = 0
				for i in range(l - 1, -1, -1):
					if a[i] >= b[0]:
						break
					m = a[i]
					f2 = i
				return m + ''.join(a[:f2]) + ''.join(a[f2 + 1:])
			else:
				return b[0] + t
		else:
			m = '9'
			f2 = 0
			for i in range(l - 1, -1, -1):
				if a[i] > b[0]:
					break
				m = a[i]
				f2 = i
			return m + ''.join(a[:f2]) + ''.join(a[f2 + 1:])
a = input()
b = input()
print(int(x(list(sorted(a)), b)))


from sys import maxsize
a = input()
b = input()
if a == b:
	print(a)
elif len(b) > len(a):
	print(''.join((str(i) for i in sorted(a, reverse=True))))
else:
	result = []
	idx = 0
	list_ = list(a)
	while idx < len(b) and b[idx] in list_:
		result.append(b[idx])
		list_.remove(b[idx])
		idx += 1
	if len(result) == len(b):
		print(''.join(map(str, result)))
	else:
		idx = result.__len__()
		try:
			mx = max((x for x in list_ if x < b[idx]))
		except ValueError as ex:
			mx = 'x'
		if mx != 'x':
			result.append(mx)
			list_.remove(mx)
			result.extend(sorted(list_, reverse=True))
			print(''.join(map(str, result)))
		else:
			while True:
				pop_ = result.pop()
				list_.append(pop_)
				try:
					mx = max((x for x in list_ if x < pop_))
				except ValueError:
					pass
				else:
					break
			list_.remove(mx)
			result.append(mx)
			result.extend(sorted(list_, reverse=True))
			print(''.join(map(str, result)))


(a, b) = (input(), input())
if len(a) < len(b):
	print(''.join(sorted(a, reverse=True)))
else:
	d = {}
	for c in a:
		d[c] = d.get(c, 0) + 1
	ans = ''
	for i in range(len(a)):
		if ans and ans < b[:i]:
			ans += ''.join(sorted(''.join([k * v for (k, v) in d.items()]), reverse=True))
			break
		for j in range(9, -1, -1):
			c = chr(ord('0') + j)
			if d.get(c, 0):
				d[c] -= 1
				if c == b[i]:
					tmp = ''.join(sorted(''.join([k * v for (k, v) in d.items()])))
					if tmp <= b[i + 1:]:
						ans += c
						break
				elif c < b[i]:
					ans += c
					break
				d[c] += 1
	print(ans)


a = sorted(input())
b = int(input())
a = a[::-1]
p = ''
while a:
	for (i, z) in enumerate(a):
		n = p + a[i] + ''.join(sorted(a[:i] + a[i + 1:]))
		if int(n) <= b:
			p += z
			a.pop(i)
			break
print(p)


a = input()
b = input()
length_of_a = len(a)
length_of_b = len(b)
found_digit = False
chk_finnish = False
appended_digit_count = 0
n = {}
num = []
for i in range(0, 10):
	n[i] = 0
for i in range(0, length_of_a):
	c = int(a[i])
	n[c] += 1
if length_of_a < length_of_b:
	num = sorted(a, reverse=True)
	for i in range(0, length_of_a):
		print(num[i], end='')
else:
	for i in range(0, length_of_b):
		digit = int(b[i])
		if n[digit] > 0:
			num.append(digit)
			n[digit] -= 1
			appended_digit_count += 1
		else:
			j = digit - 1
			while j > -1:
				if n[j] > 0:
					num.append(j)
					appended_digit_count += 1
					n[j] -= 1
					found_digit = True
					chk_finnish = True
					break
				j -= 1
			if found_digit:
				j = 9
				while j > -1:
					if n[j] > 0:
						digit_count = n[j]
						for k in range(0, digit_count):
							num.append(j)
							n[j] -= 1
							appended_digit_count += 1
					j -= 1
				if chk_finnish:
					break
			else:
				found_digit = False
				while found_digit == False:
					pop_up = num[appended_digit_count - 1]
					del num[-1]
					j = pop_up - 1
					n[pop_up] += 1
					appended_digit_count -= 1
					while j > -1:
						if n[j] > 0:
							num.append(j)
							appended_digit_count += 1
							n[j] -= 1
							found_digit = True
							break
						j -= 1
				j = 9
				while j > -1:
					if n[j] > 0:
						digit_count = n[j]
						for k in range(0, digit_count):
							num.append(j)
							appended_digit_count += 1
					j -= 1
				break
	for i in range(0, length_of_b):
		print(num[i], end='')


a = list(input())
b = int(input())
a.sort()
a = a[::-1]
prefix = ''
while len(a):
	for i in range(len(a)):
		num = prefix + a[i] + ''.join(sorted(a[:i] + a[i + 1:]))
		if int(num) <= b:
			prefix += a[i]
			a = a[:i] + a[i + 1:]
			break
print(prefix)


import sys
import math
t = 1
for _ in range(t):
	a = input()
	b = input()
	dp = [0] * 11
	for i in a:
		dp[int(i)] += 1
	if len(b) > len(a):
		ans = ''
		for i in range(len(a)):
			for j in range(9, -1, -1):
				if dp[j] != 0:
					ans += str(j)
					dp[j] -= 1
					break
	elif len(a) == len(b):
		ans = ''
		a1 = []
		cmpr = ''
		i = 0
		while i < len(a):
			cmpr += b[i]
			if i == 0:
				flag = 0
				for j in range(9, 0, -1):
					if ans + str(j) <= cmpr and dp[j] != 0:
						flag = 1
						dp[j] -= 1
						ans += str(j)
						a1.append(j)
						break
				if flag == 0:
					dp[1] -= 1
					a1.append(1)
					ans += '1'
			else:
				flag = 0
				for j in range(9, -1, -1):
					if ans + str(j) <= cmpr and dp[j] != 0:
						flag = 1
						ans += str(j)
						a1.append(j)
						dp[j] -= 1
						break
				if flag == 0:
					ch = 0
					for i1 in range(i - 1, -1, -1):
						if ch == 1:
							break
						for j1 in range(int(ans[i1]) - 1, -1, -1):
							if i1 == 0:
								if j1 > 0 and dp[j1] != 0:
									dp[a1[i1]] += 1
									dp[j1] -= 1
									index = i1
									a1.pop()
									a1.append(j1)
									ch = 1
									break
							elif dp[j1] != 0:
								dp[a1[i1]] += 1
								dp[j1] -= 1
								a1.pop()
								index = i1
								a1.append(j1)
								ch = 1
								break
							if ch == 1:
								break
						if ch == 1:
							break
						val = a1.pop()
						dp[val] += 1
					ans = ''
					cmpr = ''
					dp = [0] * 11
					for i1 in range(len(a)):
						dp[int(a[i1])] += 1
					for i1 in range(len(a1)):
						dp[a1[i1]] -= 1
					for i1 in range(len(a1)):
						ans += str(a1[i1])
						cmpr += b[i1]
					i = index
			i += 1
	print(ans)


a = list(input())
b = int(input())
a.sort(reverse=True)
ans = ''
while a:
	for i in range(len(a)):
		j = a[:i] + a[i + 1:]
		l = ans + a[i] + ''.join(sorted(j))
		if int(l) <= b:
			ans = ans + a[i]
			del a[i]
			break
print(ans)


s = sorted(input())
m = int(input())
h = len(s)
fun = lambda y: int(''.join(y))
for x in range(0, h):
	for i in range(x, h):
		(s[x], s[i]) = (s[i], s[x])
		temp = fun(s)
		if temp > m:
			(s[x], s[i]) = (s[i], s[x])
print(fun(s))


from string import digits
from collections import Counter
a = input()
b = input()
ca = Counter(a)
l = list()
if len(b) > len(a):
	for i in digits[::-1]:
		if i in ca:
			l.extend(i * ca[i])
else:

	def asd(i, s):
		if i == len(b):
			return True
		if s:
			for j in digits[::-1]:
				if j in ca and ca[j] > 0:
					l.extend(j * ca[j])
			return True
		else:
			for j in digits[:int(b[i]) + 1][::-1]:
				if j in ca and ca[j] > 0:
					ca[j] -= 1
					l.append(j)
					if asd(i + 1, j != b[i]):
						return True
					ca[j] += 1
					l.pop()
			return False
	asd(0, False)
print(''.join(l))


def f(n):
	if n <= 1:
		return 1
	else:
		return n * f(n - 1)

def g(ls, i, s):
	if len(ls) == 1:
		return 10 * s + ls[0]
	else:
		k = f(len(ls) - 1)
		return g(ls[:i // k] + ls[i // k + 1:], i % k, 10 * s + ls[i // k])
a = int(input())
b = int(input())
ls = list(sorted(map(int, str(a))))
l = 0
r = f(len(ls)) - 1
if g(ls, r, 0) <= b:
	ans = g(ls, r, 0)
else:
	while 1 < r - l:
		c = (l + r) // 2
		if b < g(ls, c, 0):
			r = c
		else:
			l = c
	ans = g(ls, l, 0)
print(ans)


class Solution:

	def canWork(self, pre, a, b):
		return int(pre + ''.join(a)) <= b

	def step(self, pre, a, b):
		for i in range(len(a) - 1, -1, -1):
			pre2 = pre + a[i]
			a2 = a[:i] + a[i + 1:]
			if self.canWork(pre2, a2, b):
				return (pre2, a2)
		raise Exception('Broken')

	def solve(self, a, b):
		a = list(a)
		b = int(b)
		pre = ''
		a.sort()
		while a:
			(pre, a) = self.step(pre, a, b)
		return pre

def main():
	sol = Solution()
	print(sol.solve(input(), input()))
main()


def comp(a, b):
	x = len(a)
	s1 = ''
	s2 = ''
	for i in range(x):
		s1 += str(a[i])
		s2 += str(b[i])
	if s1 > s2:
		return 1
	else:
		return 0
a = list(input(''))
b = list(input(''))
cnt = [0] * 10
n = len(a)
m = len(b)
sol = ''
for i in range(n):
	a[i] = int(a[i])
	cnt[a[i]] += 1
if n != m:
	a.sort(reverse=True)
	for i in a:
		sol += str(i)
	print(sol)
else:
	a.sort()
	for i in range(n):
		b[i] = int(b[i])
	for i in range(n - 1):
		for j in range(i, n):
			if a[i] < a[j]:
				temp = a[i]
				a[i] = a[j]
				a[j] = temp
				if comp(a, b):
					temp = a[i]
					a[i] = a[j]
					a[j] = temp
	for i in a:
		sol += str(i)
	print(sol)


import sys
from collections import Counter
(a, b) = sys.stdin.readlines()
a = a.strip()
b = b.strip()
if len(a) < len(b):
	print(''.join(sorted(list(a), reverse=True)))
	quit()
digits = [int(x) for x in a]
c = Counter(digits)
best = None
n = len(digits)
for i in range(n + 1):
	ok = True
	d = c.copy()
	v = 0
	for j in range(i):
		x = int(b[j])
		if not d.get(x):
			ok = False
			break
		else:
			d[x] = d[x] - 1
			v = v * 10 + x
	if not ok:
		continue
	if i < n:
		sub = None
		for j in range(int(b[i])):
			if d.get(j):
				sub = j
		if sub is None:
			continue
		d[sub] -= 1
		v = v * 10 + sub
	for (x, y) in sorted(list(d.items()), reverse=True):
		for j in range(y):
			v = v * 10 + x
	if ok:
		best = max(best or v, v)
print(best)


from sys import stdin, stdout
a = str(stdin.readline().strip())
b = str(stdin.readline().strip())
dig = []
for x in range(10):
	dig.append(0)
for x in a:
	dig[int(x)] += 1
if len(a) < len(b):
	for x in range(9, -1, -1):
		stdout.write(str(x) * dig[x])
else:
	ans = ''
	cnd = False
	dig1 = dig
	for x in b:
		if dig1[int(x)] > 0:
			ans += x
			dig1[int(x)] -= 1
		else:
			for k in range(int(x) - 1, -1, -1):
				if dig1[k] > 0:
					ans += str(k)
					dig1[k] -= 1
					cnd = True
					for i in range(9, -1, -1):
						ans += str(i) * dig1[i]
					break
			if cnd:
				break
			else:
				for i in range(len(ans) - 1, -1, -1):
					dig1[int(b[i])] += 1
					for j in range(int(b[i]) - 1, -1, -1):
						if dig1[j] > 0:
							cnd = True
							ans = ans[:i]
							ans += str(j)
							dig1[j] -= 1
							for k in range(9, -1, -1):
								ans += str(k) * dig1[k]
							break
					if cnd:
						break
		if cnd:
			break
	print(ans)


def main():
	a = input()
	b = input()
	if len(a) < len(b):
		a = list(a)
		a.sort(reverse=True)
		print(''.join(a))
		return

	def solve(i, a: list):
		if i == len(b):
			return ''
		if a.__contains__(b[i]):
			a.remove(b[i])
			suf = solve(i + 1, a)
			if suf is not None:
				return b[i] + suf
			a.append(b[i])
		best = ''
		for c in a:
			if c < b[i] and c > best:
				best = c
		if best == '':
			return None
		a.remove(best)
		a.sort(reverse=True)
		return best + ''.join(a)
	a = list(a)
	print(solve(0, a))
main()


from sys import stdin as si
from collections import Counter as c

class Solution:

	def bazinga(self, feq, m, ct, down, ans):
		if ct == len(m):
			print(ans)
			return 1
		if down:
			begin_with = 9
		else:
			begin_with = int(m[ct])
		for i in range(begin_with, -1, -1):
			i = str(i)
			if i in feq and feq[i] > 0:
				feq[i] -= 1
				if int(i) != begin_with:
					down = 1
				got = self.bazinga(feq, m, ct + 1, down, ans + i)
				if got:
					return
				feq[i] += 1

	def precompute_digits(self, n, m):
		if len(n) < len(m):
			print(''.join(sorted(n, reverse=True)))
			return
		feq = c(n)
		(count, down) = (0, False)
		self.bazinga(feq, m, count, down, '')
		return

	def precomp_dig(self, a, b):
		a = sorted(a)
		(r, p) = (range(len(a)), lambda x: int(''.join(x)))
		for i in r:
			for j in r[i:]:
				(a[i], a[j], c) = (a[j], a[i], p(a))
				if not c <= p(a) <= p(b):
					(a[i], a[j]) = (a[j], a[i])
		print(p(a))
		return
n = si.readline().strip()
m = si.readline().strip()
S = Solution()
S.precomp_dig(n, m)


from typing import List
a: List[str] = sorted(list(input()), reverse=True)
b: str = input()
prefix: str = ''

def solve(a: List[str], b: str, prefix: str) -> str:
	if len(a) == 0:
		return prefix
	for (i, elem) in enumerate(a):
		candidate = prefix + elem + ''.join(sorted(a[:i] + a[i + 1:]))
		if int(candidate) <= int(b):
			return solve(a[:i] + a[i + 1:], b, prefix + elem)
	raise Exception('Unhandled recursive case.')
print(solve(a, b, prefix))


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
from itertools import permutations
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
a = sorted(input())
b = int(input())
a = a[::-1]
p = ''
while a:
	for (i, z) in enumerate(a):
		n = p + a[i] + ''.join(sorted(a[:i] + a[i + 1:]))
		if int(n) <= b:
			p += z
			a.pop(i)
			break
print(p)


a = [int(i) for i in list(input())]
b = [int(i) for i in list(input())]
if len(a) < len(b):
	a.sort(reverse=True)
	ans = 0
	for i in range(len(a)):
		ans = ans * 10 + a[i]
	print(ans)
else:
	ans = 0
	n = len(a)
	count = [0] * 10
	for i in range(n):
		count[a[i]] += 1
	i = 0
	while i < n:
		x = b[i]
		if count[x] > 0:
			ans = ans * 10 + x
			count[x] -= 1
			i += 1
		else:
			break
	if i == n:
		print(ans)
		exit(0)
	x = b[i]
	flag = False
	for j in range(x - 1, -1, -1):
		if count[j] > 0:
			ans = ans * 10 + j
			count[j] -= 1
			flag = True
			break
	if flag:
		for j in range(9, -1, -1):
			while count[j] > 0:
				ans = ans * 10 + j
				count[j] -= 1
	else:
		while not flag:
			t = ans % 10
			ans = ans // 10
			count[t] += 1
			for i in range(t - 1, -1, -1):
				if count[i] > 0:
					count[i] -= 1
					flag = True
					ans = ans * 10 + i
					break
		for j in range(9, -1, -1):
			while count[j] > 0:
				ans = ans * 10 + j
				count[j] -= 1
	print(ans)


import copy
(Num1, Num2) = (sorted(list(input())), list(input()))
Num1.reverse()
(Temp1, Temp2, i, j, Result) = (copy.copy(Num1), copy.copy(Num2), 0, 0, [])
if len(Temp1) < len(Temp2):
	print(''.join(Temp1))
	exit()
while True:
	if i + 1 > len(Temp1):
		Temp1.append(Result[len(Result) - 1])
		Temp1.sort()
		Temp1.reverse()
		i = Temp1.index(Result[len(Result) - 1]) + Temp1.count(Result[len(Result) - 1])
		del Result[len(Result) - 1]
		j -= 1
	elif i + 1 == len(Temp1):
		if Temp1[i] < Temp2[j]:
			print(''.join(Result) + Temp1[i] + ''.join(Temp1[:i]))
			exit()
		elif Temp1[i] == Temp2[j]:
			if j == len(Temp2) - 1:
				print(''.join(Result) + Temp1[i])
				exit()
			elif j == 0:
				Start = i
			Result.append(Temp1[i])
			del Temp1[i]
			(i, j) = (0, j + 1)
		else:
			Temp1.append(Result[len(Result) - 1])
			Temp1.sort()
			Temp1.reverse()
			i = Temp1.index(Result[len(Result) - 1]) + Temp1.count(Result[len(Result) - 1])
			del Result[len(Result) - 1]
			j -= 1
	elif Temp1[i] < Temp2[j]:
		print(''.join(Result) + Temp1[i] + ''.join(Temp1[:i] + Temp1[i + 1:]))
		exit()
	elif Temp1[i] == Temp2[j]:
		if j == 0:
			Start = i
		Result.append(Temp1[i])
		del Temp1[i]
		(i, j) = (0, j + 1)
	elif Temp1[i] > Temp2[j]:
		i += 1


def solve(al, bl, lim):
	if lim:
		m = -1
		sm = -1
		bar = bl[0]
		for i in al:
			if i <= bar:
				if i > m:
					sm = m
					m = i
				elif i < m and i > sm:
					sm = i
		if m == -1:
			return [-1]
		if len(al) == 1:
			if al[0] <= bl[0]:
				return al
			else:
				return [-1]
		j = al.copy()
		j.remove(m)
		if m == bar:
			if solve(j, bl[1:], lim)[-1] == -1:
				if sm == -1:
					return [-1]
				j = al.copy()
				j.remove(sm)
				return join([sm], solve(j, bl[1:], False))
			else:
				return join([m], solve(j, bl[1:], lim))
		return join([m], solve(j, bl[1:], False))
	else:
		maxf = 0
		for i in al:
			if i > maxf:
				maxf = i
		if len(al) > 1:
			al.remove(maxf)
			return join([maxf], solve(al, bl[1:], lim))
		else:
			return [maxf]

def join(j, k):
	for i in k:
		j.append(i)
	return j
join([0], [1, 2])
cl = [0, 1, 2, 3]
cl[1:]

def nDigs(a):
	c = 0
	while float(a) / 10 ** c >= 1:
		c = c + 1
	return c
a = int(input())
b = int(input())
al = []
for i in range(0, nDigs(a)):
	al.append(int((a % 10 ** (i + 1) - a % 10 ** i) / 10 ** i))
bl = []
for i in range(0, nDigs(b)):
	bl.append(int((b % 10 ** (i + 1) - b % 10 ** i) / 10 ** i))
al.reverse()
bl.reverse()
ret = 0
if len(al) < len(bl):
	ret = solve(al, bl, False)
else:
	ret = solve(al, bl, True)
r = 0
for i in range(0, len(ret)):
	r = r + ret[i] * 10 ** (len(ret) - i - 1)
print(int(r))


a = input()
b = input()
if len(a) < len(b):
	print(''.join(sorted(a, reverse=True)))
else:
	b = int(b)
	digits = sorted(a, reverse=True)
	curr = ''
	temp = ''
	while digits:
		for i in range(len(digits)):
			temp += digits[i]
			suffix = ''.join(sorted(digits[:i] + digits[i + 1:]))
			if int(temp + suffix) <= b:
				curr = temp
				digits.pop(i)
				break
			temp = curr
	print(curr)


a = ''.join(reversed(sorted(input())))
b = int(input())
r = ''
while len(a) > 0:
	for i in range(len(a)):
		n = r + a[i] + ''.join(sorted(a[:i] + a[i + 1:]))
		if int(n) <= b:
			r += a[i]
			a = a[:i] + a[i + 1:]
			break
print(r)


def get(g):
	s = [str(i) for i in g]
	num = int(''.join(s))
	return num
a = input()
b = input()
bb = int(b)
mark = [0 for i in range(len(a))]
c = a
f = []
g = []
for i in range(0, len(a)):
	g.append(a[i])
g.sort()
g.reverse()
num = get(g)
index = []
if num <= bb:
	print(num)
	exit(0)
for i in range(0, min(len(a), len(b))):
	mx = '-1'
	idx = 0
	for j in range(0, len(a)):
		if mark[j] == 0 and a[j] <= b[i]:
			if a[j] > mx:
				mx = a[j]
				idx = j
	if mx == '-1':
		rem = []
		while True and len(f) > 0:
			ma = '-1'
			id = 0
			for j in range(0, len(a)):
				if mark[j] == 0 and a[j] < f[-1]:
					if a[j] > ma:
						ma = a[j]
						id = j
			if ma == '-1':
				mark[index.pop()] = 0
				f.pop()
				continue
			else:
				mark[index.pop()] = 0
				f.pop()
				f.append(ma)
				mark[id] = 1
				break
		for j in range(0, len(a)):
			if mark[j] == 0:
				rem.append(a[j])
		rem.sort()
		rem.reverse()
		for j in rem:
			f.append(j)
		print(get(f))
		exit(0)
	f.append(mx)
	mark[idx] = 1
	index.append(idx)
	if mx < b[i] and mx != '-1':
		break
rem = []
for i in range(0, len(a)):
	if mark[i] == 0:
		rem.append(a[i])
rem.sort()
rem.reverse()
for i in rem:
	f.append(i)
print(get(f))


def check(s, a):
	st = ''
	for i in range(len(s)):
		st += s[i]
	st = int(st)
	if st > a:
		return False
	else:
		return True
a = input()
b = input()
s = []
ans = ''
for i in range(len(a)):
	s.append(a[i])
s.sort()
if len(b) > len(a):
	for i in range(len(s)):
		print(s[len(s) - i - 1], end='')
else:
	for i in range(len(a)):
		j = 0
		temp2 = -1
		while j < len(s) - 1 and s[j + 1] <= b[i]:
			j += 1
			if s[j] != s[j - 1]:
				temp2 = j - 1
		temp = s[j]
		s.remove(s[j])
		if i == len(a) - 1 or check(s, int(b[i + 1:len(b)])) or temp < b[i]:
			ans += temp
			if ans[i] < b[i]:
				for k in range(len(s)):
					ans += s[len(s) - k - 1]
		else:
			s.append(temp)
			s.sort()
			temp2 = s[temp2]
			ans += temp2
			s.remove(temp2)
			for k in range(len(s)):
				ans += s[len(s) - k - 1]
		if len(ans) == len(a):
			break
print(ans)


a = input()
b = input()

def lessThan(pos, b, digits):
	cur_num = ''
	canEqual = True
	for i in range(pos):
		if b[i] in digits:
			cur_num += b[i]
			digits.remove(b[i])
		else:
			canEqual = False
			break
	if not canEqual:
		canLess = False
		m = ''
		for elem in digits:
			if elem < b[len(cur_num)] and elem >= m:
				m = elem
				canLess = True
		if canLess:
			cur_num += m
			digits.remove(m)
		for elem in digits:
			cur_num += elem
	else:
		canLess = False
		m = ''
		for elem in digits:
			if elem < b[pos] and elem >= m:
				m = elem
				canLess = True
		if canLess:
			cur_num += m
			digits.remove(m)
		for elem in digits:
			cur_num += elem
	return cur_num
digits = list(map(str, a))
digits.sort()
digits.reverse()
ans = 0
for pos in range(len(b)):
	cur_ans = lessThan(pos, b, digits[:])
	if int(cur_ans) <= int(b):
		ans = max(ans, int(cur_ans))
if len(a) < len(b):
	print(*digits, sep='')
else:
	print(ans)


import os
import sys
from io import BytesIO, IOBase

def main():
	a = list(map(int, input().rstrip()))
	b = list(map(int, input().rstrip()))
	(ans, la, lb) = ([], len(a), len(b))
	if la != lb:
		print(*sorted(a, reverse=True), sep='')
	else:
		for i in range(lb):
			if b[i] in a:
				ans.append(b[i])
				a.remove(b[i])
			else:
				ma = -1
				for j in a:
					if j < b[i]:
						ma = max(ma, j)
				if ma != -1:
					ans.append(ma)
					a.remove(ma)
				else:
					i -= 1
					while ans:
						a.append(ans.pop())
						ma = -1
						for j in a:
							if j < b[i]:
								ma = max(ma, j)
						if ma != -1:
							ans.append(ma)
							a.remove(ma)
							break
						i -= 1
				a.sort()
				while a:
					ans.append(a.pop())
				break
		print(''.join((str(i) for i in ans)))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


a = list(input())
b = int(input())
a.sort()
for i in range(len(a) - 1):
	for j in range(len(a) - 1, i - 1, -1):
		z = a[:i] + a[j:j + 1] + a[i:j] + a[j + 1:]
		if int(''.join(z)) <= b:
			a = z
			break
for i in a:
	print(i, end='')


a = sorted(input())
b = int(input())
a = a[::-1]
k = ''
while len(a) > 0:
	for i in range(len(a)):
		num = k + a[i] + ''.join(sorted(a[:i] + a[i + 1:]))
		if int(num) <= b:
			k += a[i]
			a = a[:i] + a[i + 1:]
			break
print(k)


from collections import Counter
a = input()
b = input()
if len(a) < len(b):
	print(''.join(sorted(a)[::-1]))
	exit()
n = len(a)
cnt = Counter(a)

def f(i=0, check=False):
	if i == n:
		return []
	for j in sorted(cnt)[::-1]:
		if (check or j <= b[i]) and cnt[j]:
			cnt[j] -= 1
			res = f(i + 1, check or j < b[i])
			if len(res) + i + 1 == n:
				res.append(j)
				return res
			cnt[j] += 1
	return []
print(''.join(f()[::-1]))


from copy import copy

def check(a, b):
	a = int(''.join(sorted(a)))
	b = int(b[1:])
	return a <= b

def get(a, b):
	global ans
	global ret
	if a == b:
		ans += list(a)
		ret = True
		return ans
	a = list(a)
	if a == list():
		ret = True
		return ans
	temp = [el for el in a if int(el) <= int(b[0])]
	m = max(temp)
	c = copy(a)
	c.remove(m)
	if m == b[0]:
		if check(c, b):
			ans.append(m)
			get(''.join(c), b[1:])
			if ret:
				return ans
		else:
			while m in temp:
				temp.remove(m)
			m = max(temp)
			d = copy(a)
			d.remove(m)
			ans.append(m)
			ans += sorted(d, reverse=True)
			ret = True
			return ans
	else:
		ans.append(m)
		ans += sorted(c, reverse=True)
		ret = True
		return ans
a = input()
b = input()
ans = list()
ret = False
if len(a) < len(b):
	print(''.join(sorted(a, reverse=True)))
elif a == b:
	print(a)
else:
	print(int(''.join(get(a, b))))


from copy import copy

def read_int():
	return int(input())

def read_str():
	return input()

def read_list(type=int):
	return list(map(type, input().split()))

def print_list(x):
	print(len(x), ' '.join(map(str, x)))
N = 100123
b = read_str()
a = read_str()
best = None
b = list(b)

def is_good(x):
	if x[0] == '0':
		return False
	return int(x) <= int(a)

def f(prefix, left):
	global best
	if not left:
		return
	for d in left:
		number = (prefix + d).strip()
		dleft = copy(left)
		del dleft[dleft.index(d)]
		cand = number + ''.join(sorted(dleft))
		if is_good(cand) and (not best or int(cand) > int(best)):
			best = cand
		cand = number + ''.join(reversed(sorted(dleft)))
		if is_good(cand) and (not best or int(cand) > int(best)):
			best = cand
	dd = None
	for d in sorted(left):
		if d <= a[len(prefix)]:
			dd = d
	if dd:
		del left[left.index(dd)]
		return f(prefix + dd, left)
f('', b)
print(best if best else b)


b = [int(i) for i in list(input())]
a = [int(i) for i in list(input())]
if len(b) < len(a):
	print(''.join([str(i) for i in sorted(b, key=lambda x: -x)]))
	exit()
from collections import Counter
bs = Counter(b)
mp = 0
while mp < len(a) and bs[a[mp]] > 0:
	bs[a[mp]] -= 1
	mp += 1
if mp == len(a):
	print(''.join((str(i) for i in a)))
	exit()
ms = 0
for s in range(1, mp + 1):
	bs = Counter(b)
	for i in range(s):
		bs[a[i]] -= 1
	nl = a[s] - 1
	while nl >= 0 and bs[nl] == 0:
		nl -= 1
	if nl == -1:
		continue
	else:
		ms = s
ans = []
bs = Counter(b)
for i in range(ms):
	bs[a[i]] -= 1
	ans.append(a[i])
nl = a[ms] - 1
while nl >= 0 and bs[nl] == 0:
	nl -= 1
ans.append(nl)
bs[nl] -= 1
d1 = [[i for _ in range(bs[i])] for i in bs]
r = []
for l in d1:
	r += l
r = sorted(r, key=lambda x: -x)
ans += r
print(''.join([str(i) for i in ans]))


a = int(input())
b = int(input())
D = [0] * 10
while a:
	D[a % 10] += 1
	a //= 10
cur = 0

def check():
	global cur
	ans = cur
	for i in range(10):
		for _ in range(D[i]):
			ans = ans * 10 + i
	return b >= ans

def dfs():
	for i in range(10):
		if D[9 - i]:
			D[9 - i] -= 1
			global cur
			cur = cur * 10 + 9 - i
			if check():
				return dfs()
			D[9 - i] += 1
			cur //= 10
dfs()
print(cur)


a = list(map(int, list(input())))
b = list(map(int, list(input())))
answer = [0 for _ in range(len(b))]

def solve(a, whatPos, flag):
	global b, answer
	pos = len(a)
	minNumber = 10
	if pos != 0:
		for x in range(pos - 1, -1, -1):
			if (a[x] <= b[whatPos] or flag) and minNumber != a[x]:
				minNumber = a[x]
				copyFlag = flag or a[x] < b[whatPos]
				copyA = a.copy()
				copyA.pop(x)
				answer[whatPos] = a[x]
				if solve(copyA, whatPos + 1, copyFlag):
					return True
		return False
	return True
index = 0
flag = False
if len(b) > len(a):
	index = len(b) - len(a)
	flag = True
solve(sorted(a), index, flag)
flag = False
for x in answer:
	if x != 0 or flag:
		print(x, end='')
		flag = True


import math
from sys import stdin
a = stdin.readline()
b = stdin.readline()
arrayA = []
arrayB = []
for letter in a:
	if letter != '\n':
		arrayA.append(int(letter))
for letter in b:
	if letter != '\n':
		arrayB.append(int(letter))
if len(arrayB) > len(arrayA):
	arrayA = sorted(arrayA, reverse=True)
else:
	i = 0
	while i < len(arrayB) - 1:
		if arrayB[i] in arrayA[i:]:
			idx = arrayA[i:].index(arrayB[i]) + i
			temp = arrayA[idx]
			arrayA[idx] = arrayA[i]
			arrayA[i] = temp
			arrayA[i + 1:] = sorted(arrayA[i + 1:])
			crt = True
			for n in range(i + 1, len(arrayA)):
				if arrayA[n] < arrayB[n]:
					break
				elif arrayA[n] > arrayB[n]:
					crt = False
			if crt == False:
				tempMax = 0
				for letter in arrayA[i:]:
					if letter < arrayB[i] and letter > tempMax:
						tempMax = letter
				idx = arrayA[i:].index(tempMax) + i
				arrayA[idx] = arrayA[i]
				arrayA[i] = tempMax
				arrayA[i + 1:] = sorted(arrayA[i + 1:], reverse=True)
				i = len(arrayA)
		elif arrayB[i] not in arrayA[i:]:
			tempMax = 0
			for letter in arrayA[i:]:
				if letter < arrayB[i] and letter > tempMax:
					tempMax = letter
			idx = arrayA[i:].index(tempMax) + i
			arrayA[idx] = arrayA[i]
			arrayA[i] = tempMax
			arrayA[i + 1:] = sorted(arrayA[i + 1:], reverse=True)
			i = len(arrayA)
		i += 1
value = 0
for i in range(len(arrayA)):
	value += arrayA[i] * 10 ** (len(arrayA) - 1 - i)
print(value)


a = list(map(int, input().strip().split()))[0]
b = list(map(int, input().strip().split()))[0]
dp = dict()
for i in str(a):
	digits = int(i)
	if digits in dp:
		dp[digits] += 1
	else:
		dp[digits] = 1
order = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

def maximum(before, dp, low):
	global order
	temp = dp.copy()
	before += str(low)
	temp[low] -= 1
	answer = before
	for key in order:
		if key in temp:
			answer += str(key) * temp[key]
	return int(answer)
if len(str(a)) < len(str(b)):
	answer = ''
	for key in order:
		if key in dp:
			answer += str(key) * dp[key]
	print(int(answer))
else:
	answer = 0
	before = '0'
	for digits in str(b):
		for low in range(int(digits) - 1, -1, -1):
			if low == 0 and before == '0':
				break
			if low in dp:
				answer = max(answer, maximum(before, dp, low))
				break
		if int(digits) in dp:
			before += digits
			dp[int(digits)] -= 1
			if dp[int(digits)] == 0:
				dp.pop(int(digits))
		else:
			break
	answer = max(answer, int(before))
	print(answer)


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(100000000)
	threading.stack_size(40960000)
	thread = threading.Thread(target=main)
	thread.start()
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def getKey(item):
	return item[1]

def sort2(l):
	return sorted(l, key=getKey)

def d2(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def ntl(n):
	return [int(i) for i in str(n)]

def powerMod(x, y, p):
	res = 1
	x %= p
	while y > 0:
		if y & 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def main():
	a = si()
	b = si()
	fff = int(b)
	x = []
	for i in a:
		x.append(int(i))
	y = []
	for i in b:
		y.append(int(i))
	x.sort(reverse=True)
	if len(y) > len(x):
		s = ''
		for j in x:
			s += str(j)
		print(s)
		exit()
	f = [0] * 26
	for i in a:
		f[int(i)] += 1
	l = list(a)
	l.sort()
	b = list(b)
	ans = []
	flag = 0
	n = len(x)
	for i in range(n):
		for k in range(9, -1, -1):
			if f[k] == 0:
				continue
			if k <= y[i]:
				del l[l.index(str(k))]
				l.sort()
				if [str(k)] + l <= b[i:] or k < y[i]:
					ans += [str(k)]
					f[k] -= 1
					if k < y[i]:
						l = sorted(l, reverse=True)
						ans = ans + l
						flag = 1
					break
				else:
					l.append(str(k))
					l.sort()
		if flag:
			break
	print(''.join(ans))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from copy import deepcopy
a = list(map(int, list(input())))
b = list(map(int, list(input())))
cnt1 = [0] * 10
cnt2 = [0] * 10
ans = []
if len(a) != len(b):
	print(''.join(map(str, sorted(a, reverse=True))))
	exit()
for i in range(len(b) + 1):
	ok = 1
	tmp = deepcopy(a)
	for j in range(i):
		if b[j] in tmp:
			tmp.pop(tmp.index(b[j]))
		else:
			ok = 0
			break
	if not ok:
		continue
	pls = -1
	ind = -1
	for j in range(len(tmp)):
		if tmp[j] < b[i]:
			if tmp[j] > pls:
				ind = j
				pls = tmp[j]
	if pls == -1 and len(tmp) != 0:
		continue
	else:
		if len(tmp) > 0:
			tmp.pop(ind)
		if i == len(b):
			ans.append(''.join(map(str, b[:i])))
		else:
			ans.append(''.join(map(str, b[:i])) + str(pls) + ''.join(map(str, sorted(tmp, reverse=True))))
print(max(ans))


a = input()
b = input()
if len(b) > len(a):
	tmp = list(a)
	tmp.sort(reverse=True)
	for i in tmp:
		print(i, end='')
	exit(0)
sa = [0] * 10
for i in a:
	sa[int(i)] += 1

def tolow():
	tmp = ''
	for i in range(0, 10):
		tmp += str(i) * sa[i]
	return tmp

def tobig():
	tmp = ''
	for i in range(9, -1, -1):
		tmp += str(i) * sa[i]
	return tmp
nakop = ''
for i in range(len(b)):
	tmp = int(b[i])
	if sa[tmp] > 0:
		sa[tmp] -= 1
		cur = int(nakop + b[i] + tolow())
		if cur <= int(b):
			nakop += str(b[i])
			continue
		else:
			sa[tmp] += 1
			for j in range(tmp - 1, -1, -1):
				if sa[j]:
					sa[j] -= 1
					print(nakop + str(j) + tobig())
					exit(0)
	else:
		for j in range(tmp - 1, -1, -1):
			if sa[j]:
				sa[j] -= 1
				print(nakop + str(j) + tobig())
				exit(0)
print(nakop)


def permuteDigits(a, b):
	n = len(a)
	if len(a) < len(b):
		return a
	i = 0
	c = 0
	t = a[0]
	flag = 0
	lastind = []
	while i < len(a) and i < len(b) and (a[i] >= b[i]):
		if c == n:
			i = i - 1
			t = a[i]
			a = a[:i] + a[i + 1:]
			a.insert(lastind.pop(), t)
			flag = 1
			c = i
		elif flag == 0 and a[c] == b[i] or a[c] < b[i]:
			lastind.append(c)
			t = a[c]
			a = a[:c] + a[c + 1:]
			a.insert(i, t)
		else:
			c = c + 1
		if a[i] < b[i]:
			break
		elif flag == 0 and a[i] == b[i]:
			i = i + 1
			c = i
	return a
aa = input()
bb = input()
a = []
b = []
for i in aa:
	a.append(int(i))
for i in bb:
	b.append(int(i))
a.sort(reverse=True)
ans = permuteDigits(a, b)
s = ''
for i in ans:
	s = s + str(i)
print(int(s))


def main():
	import sys
	input = sys.stdin.readline
	a = int(input())
	b = int(input())
	a = list(str(a))
	a.sort()
	ans = []
	while a:
		for i in range(len(a) - 1, -1, -1):
			c = ans + [a[i]] + a[:i] + a[i + 1:]
			if int(''.join(c)) <= b:
				ans.append(a[i])
				a.pop(i)
				break
	print(''.join(ans))
main()


from random import randint
from functools import reduce

def can_place(cur, freq):
	counts = list.copy(freq)
	counts[int(cur[-1])] -= 1
	counts = sorted(reduce(lambda x, y: x + y, [[str(i)] * counts[i] for i in range(10) if counts[i] > 0], []))
	return cur + ''.join(counts)
n = int(input())
b = int(input())
length = len(str(n))
freq = [0] * 10
for i in str(n):
	freq[int(i)] += 1
ans = ''
for i in reversed(range(length)):
	for j in range(9, -1, -1):
		if freq[j] == 0:
			continue
		cur_ans = int(can_place(ans + str(j), freq))
		if cur_ans > b:
			continue
		else:
			ans += str(j)
			freq[j] -= 1
			break
print(ans)


s1 = input()
s2 = input()
arr = list(s1)
arr.sort(reverse=True)
if len(s2) > len(s1):
	t = ''
	for i in arr:
		t += i
	print(t)
else:
	t = ''
	l = len(s1)
	for i in range(l):
		index = -1
		ma = -1
		for j in range(len(arr)):
			temp = arr[j]
			tt = []
			for k in range(len(arr)):
				if k != j:
					tt.append(arr[k])
			tt.sort()
			for k in tt:
				temp += k
			temp = t + temp
			if int(s2) >= int(temp):
				if int(arr[j]) > ma:
					ma = int(arr[j])
					index = j
		t += arr[index]
		del arr[index]
	print(t)


global a_arr, b_arr, cnta, cntb, enumerate, numa, ans

def toarra(x):
	global cnta
	i = 0
	while x > 0:
		a_arr[i] = x % 10
		numa[x % 10] += 1
		x = x // 10
		i += 1
	cnta = i - 1

def toarrb(x):
	global cntb
	i = 0
	while x > 0:
		b_arr[i] = x % 10
		x = x // 10
		i += 1
	cntb = i - 1

def anstonum():
	w = 0
	for i in range(cnta, -1, -1):
		w += 10 ** i * ans[i]
	return w
a = int(input())
b = int(input())
cnta = 0
cntb = 0
numa = [0] * 10
a_arr = [0] * 20
b_arr = [0] * 20
toarra(a)
toarrb(b)
numa2 = [0] * 10
for i in range(10):
	numa2[i] = numa[i]
final_ans = -1
a_arr.sort(reverse=True)
if cnta < cntb:
	for i in range(cnta + 1):
		print(a_arr[i], end='')
	quit()
ans = [0] * 20
fl = 0
for i in range(cnta, -1, -1):
	if numa[b_arr[i]] > 0:
		numa[b_arr[i]] -= 1
	else:
		fl = 1
		break
last = i + 1
if fl == 0:
	last = 0
if last > cnta:
	for j in range(b_arr[cnta] - 1, -1, -1):
		if numa[j] > 0:
			numa[j] -= 1
			ans[cnta] = j
			break
	r = 9
	for j in range(cnta - 1, -1, -1):
		while numa[r] == 0:
			r -= 1
		numa[r] -= 1
		ans[j] = r
	w = anstonum()
	print(w)
	quit()
for s in range(cnta + 1, last - 1, -1):
	for i in range(10):
		numa[i] = numa2[i]
	fl = 0
	if s <= cnta:
		for i in range(cnta, s - 1, -1):
			numa[b_arr[i]] -= 1
			ans[i] = b_arr[i]
	fl = 0
	for j in range(b_arr[s - 1] - 1, -1, -1):
		if numa[j] > 0:
			numa[j] -= 1
			ans[s - 1] = j
			fl = 1
			break
	if fl == 0 and s != 0:
		continue
	r = 9
	for j in range(s - 2, -1, -1):
		while numa[r] == 0:
			r -= 1
		numa[r] -= 1
		ans[j] = r
	w = anstonum()
	if w <= b:
		final_ans = max(final_ans, w)
print(final_ans)


a = list(input())
a.sort(reverse=True)
b = int(input())
ans = ''
while len(a) > 0:
	for i in range(len(a)):
		x = ans + a[i] + ''.join(sorted(a[:i] + a[i + 1:]))
		if int(x) <= b:
			ans += a[i]
			a = a[:i] + a[i + 1:]
			break
print(ans)


def find(a, b, ans):
	if len(a) > 0:
		for i in range(len(a)):
			test = int(ans + a[i] + ''.join(sorted(a[:i] + a[i + 1:])))
			if test <= b:
				return find(a[:i] + a[i + 1:], b, ans + a[i])
	else:
		return ans
a = int(input().strip())
b = int(input().strip())
if a == b:
	print(a)
else:
	a = list(str(a))
	if len(str(b)) > len(str(a)):
		ans = ''
		for i in sorted(a)[::-1]:
			ans += str(i)
		print(ans)
	else:
		found = False
		a.sort(reverse=True)
		ans = find(a, b, '')
		print(ans)


a = int(input())
b = int(input())
adigits = []
bdigits = []
while a > 0:
	adigits.append(a % 10)
	a //= 10
while b > 0:
	bdigits.append(b % 10)
	b //= 10
adigits.sort()
adigits = adigits[::-1]
bdigits = bdigits[::-1]
flag = 0
if len(adigits) < len(bdigits):
	ans = adigits
else:
	ans = []
	for i in range(len(adigits)):
		if flag == 1:
			break
		d = bdigits[i]
		if d in adigits:
			ans.append(d)
			adigits.remove(d)
		else:
			for j in adigits:
				if j < d:
					ans.append(j)
					adigits.remove(j)
					adigits.sort()
					ans = ans + adigits[::-1]
					flag = 1
					break
			if flag:
				break
			m = min(adigits)
			while m >= ans[len(ans) - 1]:
				adigits.append(ans.pop())
				adigits.sort()
				m = min(adigits)
			adigits.append(ans.pop())
			adigits.sort()
			k = bdigits[len(ans)]
			n = max([x for x in adigits if x < k])
			ans.append(n)
			adigits.remove(n)
			adigits.sort()
			ans += adigits[::-1]
			flag = 1
			break
final = 0
for i in ans:
	final *= 10
	final += i
print(final)


import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys
a = [int(x) for x in input()]
b = [int(x) for x in input()]
ds = collections.Counter(a)
dsb = collections.Counter(b)
if ds == dsb:
	print(int(''.join(map(str, b))))
	exit(0)
if len(a) < len(b):
	ans = []
	for x in range(9, -1, -1):
		if x in ds and ds[x] > 0:
			ans.extend([x] * ds[x])
	print(''.join(map(str, ans)))
else:
	ans = float('-inf')
	for i in range(len(a)):
		dsc = {k: v for (k, v) in ds.items()}
		ansa = []
		for (j, x) in enumerate(b):
			mx = x
			my = 0 if j == 0 else -1
			if j < i:
				pass
			elif j == i:
				mx = x - 1
			else:
				mx = 9
			f = False
			for y in range(mx, my, -1):
				if y in ds and dsc[y] > 0:
					dsc[y] -= 1
					ansa.append(y)
					f = True
					break
			if not f:
				ansa = []
				break
		if ansa:
			ans = max(ans, int(''.join(map(str, ansa))))
	if ans == float('-inf'):
		print(int(''.join(map(str, b))))
	else:
		print(ans)


from sys import stdin, stdout
a = int(stdin.readline())
b = int(stdin.readline())
ans = ''
c = sorted(list(str(a)))
while c:
	for i in range(len(c) - 1, -1, -1):
		if int(''.join(list(ans) + [c[i]] + c[:i] + c[i + 1:])) <= b:
			ans += c[i]
			c.pop(i)
			break
stdout.write(str(int(ans)))


from sys import stdin, stdout
(a, b) = (list(stdin.readline().strip()), stdin.readline().strip())

def can(x, y):
	return sorted(x) <= list(y)
if len(a) < len(b):
	stdout.write(''.join(sorted(a, key=lambda i: -ord(i))) + '\n')
else:
	free = False
	a.sort(key=lambda i: -ord(i))
	for (i, c) in enumerate(b):
		if free:
			stdout.write(''.join(a))
			break
		else:
			for (j, e) in enumerate(a):
				if e == c:
					if can(a[:j] + a[j + 1:], b[i + 1:]):
						stdout.write(a.pop(j))
						break
				if e < c:
					free = True
					stdout.write(a.pop(j))
					break
	stdout.write('\n')


a = list(input())
b = list(input())
num = int(''.join(b))
a.sort()
a.reverse()
al = len(a)
ans = []
if len(a) == len(b) and len(a) != 1:
	c = []
	count = 0
	hogya = 0
	for i in range(al):
		if hogya == 1:
			o.reverse()
			f = list(c + o)
			ans.append(''.join(f))
			count += 1
			break
		t = len(a)
		j = 0
		mittal = t
		abhinhi = 0
		while t:
			if j > len(a) - 1:
				break
			if int(a[j]) <= int(b[i]):
				c.append(a[j])
				temp = a[j]
				a.remove(a[j])
				o = a.copy()
				o.sort()
				f = list(c + o)
				if temp < b[i]:
					hogya = 1
					break
				if int(''.join(f)) <= num:
					ans.append(''.join(f))
					count += 1
					break
				else:
					a.append(temp)
					c = c[:len(c) - 1]
				t -= 1
			else:
				j += 1
				t -= 1
		if mittal == len(a):
			break
	print(ans[count - 1])
elif len(a) == 1:
	print(''.join(a))
else:
	print(''.join(a))


a = input()
b = int(input())
lst = sorted(a)
c = 0
for i in range(len(lst)):
	for j in range(len(lst) - 1, i - 1, -1):
		x = lst[:i] + [lst[j]] + sorted(lst[i:j]) + lst[j + 1:]
		if int(''.join(x)) <= b and int(''.join(x)) > c:
			c = int(''.join(x))
			lst = x
print(int(''.join(lst)))


import sys, os, io
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop
from bisect import bisect_right, bisect_left
import math

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	return list(set(l))

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def si():
	return input()

def prefix_sum(arr):
	r = [0] * (len(arr) + 1)
	for (i, el) in enumerate(arr):
		r[i + 1] = r[i] + el
	return r

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

def ii():
	return int(input())

def li():
	return list(map(int, input().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
t = 1
for _ in range(t):
	a = input()
	b = input()
	ans = [a]
	a = list(a)
	b1 = b[:]
	b = list(b)
	if len(a) < len(b):
		a.sort(reverse=True)
		print(''.join(a))
		continue
	arr = [0] * 10
	for i in a:
		arr[int(i)] += 1
	f = 0
	for chota in range(len(b)):
		arr1 = arr[:]
		temp = b[:chota]
		for h in range(chota):
			if arr1[int(b[h])] <= 0:
				f = 1
				break
			else:
				arr1[int(b[h])] -= 1
		if f == 1:
			break
		aa = []
		for j in range(int(b[chota]) - 1, -1, -1):
			if arr1[j] > 0:
				temp.append(str(j))
				arr1[j] -= 1
				break
		for h in range(9, -1, -1):
			if arr1[h] > 0:
				temp += [str(h)] * arr1[h]
		ans.append(''.join(temp))
	for i in ans:
		if i <= b1:
			m = i
			break
	a.sort(reverse=True)
	ans.append(''.join(a))
	for i in ans:
		if i <= b1:
			if i > m:
				m = i
	print(m)


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop, heapify
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
from itertools import accumulate
from functools import lru_cache
M = mod = 998244353

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split()]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
a = val()
b = val()
n = len(str(a))
a = [int(i) for i in str(a)]
a.sort()
if len(str(b)) > n:
	print(*sorted(a, reverse=1), sep='')
	exit()
b = str(b)
b = [int(i) for i in b]

def makenum(s):
	return int(''.join((str(e) for e in s)))

def givemax(a, b):
	if len(a) > len(b):
		return a
	elif len(b) > len(a):
		return b
	else:
		for j in range(len(a)):
			if a[j] > b[j]:
				return a
			elif b[j] > a[j]:
				return b
		return a

@lru_cache(None)
def dp(l, equal=1):
	if len(l) == 1:
		return str(-float('inf')) if l[0] > b[-1] and equal else str(l[0])
	if not equal:
		return ''.join((str(e) for e in sorted(l, reverse=1)))
	ans = ''
	l = list(l)
	curr = b[n - len(l)]
	for i in range(len(l)):
		if l[i] < curr and dp(tuple(l[:i] + l[i + 1:]), 0) != '-inf':
			ans = givemax(ans, str(l[i]) + dp(tuple(l[:i] + l[i + 1:]), 0))
		elif l[i] == curr and dp(tuple(l[:i] + l[i + 1:]), 1) != '-inf':
			ans = givemax(ans, str(l[i]) + dp(tuple(l[:i] + l[i + 1:]), 1))
	return str(ans)
print(dp(tuple(a), 1))


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree1:

	def __init__(self, data, default=9999999, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] > k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

def findmin(h, n):
	n.sort()
	h = int(h)
	ans = '-1'
	for i in n:
		if int(i) > h:
			break
		ans = i
	return ans
n = list(input())
n1 = list(input())
if len(n) < len(n1):
	n.sort(reverse=True)
	print(*n, sep='')
	sys.exit()
n.sort()
ans = ''
f = 0
for i in range(len(n)):
	t = i - 1
	c = 0
	r = findmin(n1[i], n)
	if r == '-1':
		while r == '-1':
			n.append(ans[-c - 1])
			r = findmin(int(n1[t]) - 1, n)
			t -= 1
			c += 1
		ans = ans[:len(ans) - c]
		ans += r
		n.remove(r)
		f = 1
		break
	n.remove(r)
	if r == n1[i]:
		ans += r
		continue
	else:
		ans += r
		f = 1
		break
if f == 1:
	n.sort(reverse=True)
	for i in n:
		ans += i
print(ans)


from collections import Counter
a = input()
b = input()

def is_subcounter(cnt1, cnt2):
	for key in cnt1:
		if key not in cnt2 or cnt1[key] > cnt2[key]:
			return False
	return True

def subtract_counters(cnt1, cnt2):
	result = Counter(cnt1)
	for (key, val) in cnt2.items():
		assert val <= result[key]
		result[key] -= val
	return result

def go():
	ca = Counter(a)
	best = None
	for pos in range(len(a) - 1, -1, -1):
		cb_before = Counter(b[:pos])
		if not is_subcounter(cb_before, ca):
			continue
		cnt_left = subtract_counters(ca, cb_before)
		for (key, val) in cnt_left.items():
			if val == 0:
				continue
			if key >= b[pos]:
				continue
			tail = sorted(''.join((key1 * (val1 if key1 != key else val1 - 1) for (key1, val1) in cnt_left.items())), reverse=True)
			curr = b[:pos] + key + ''.join(tail)
			assert curr < b
			if best is None or curr > best:
				best = curr
	assert best is not None
	return best

def solve(a, b):
	assert len(a) <= len(b)
	if len(a) < len(b):
		return ''.join(sorted(a, reverse=True))
	elif Counter(a) == Counter(b):
		return b
	else:
		return go()
print(solve(a, b))


a = list(map(int, input()))
b = list(map(int, input()))
if len(b) > len(a):
	a.sort(reverse=True)
	print(''.join(map(str, a)))
else:
	counts = [0] * 10
	for d in a:
		counts[d] += 1

	def rec(counts, i):
		if i >= len(b):
			return []
		d = b[i]
		if counts[d] > 0:
			counts[d] -= 1
			r = rec(counts, i + 1)
			if r is None:
				counts[d] += 1
			else:
				res = [d] + r
				return res
		for d in reversed(range(d)):
			if counts[d] > 0:
				counts[d] -= 1
				res = [d]
				for e in reversed(range(10)):
					for _ in range(counts[e]):
						res.append(e)
				return res
		return None
	print(''.join(map(str, rec(counts, 0))))


a = input()
b = input()
if sorted(list(a)) == sorted(list(b)):
	print(b)
elif len(a) < len(b):
	print(''.join(sorted(a)[::-1]))
else:
	digits = {}
	for x in a:
		y = int(x)
		if y in digits:
			digits[y] += 1
		else:
			digits[y] = 1
	best = 0
	for i in range(len(b)):
		digits_cpy = dict(digits)
		all_present = True
		for j in range(i):
			b_j = int(b[j])
			if b_j in digits_cpy and digits_cpy[b_j] != 0:
				digits_cpy[b_j] -= 1
			else:
				all_present = False
		if not all_present:
			continue
		found = False
		change = 0
		for z in range(int(b[i]) - 1, -1, -1):
			if z in digits_cpy and digits_cpy[z] != 0:
				found = True
				change = z
				digits_cpy[z] -= 1
				break
		if not found:
			continue
		digits_left = []
		for (key, val) in digits_cpy.items():
			digits_left += [key] * val
		result = list(b[:i]) + [change] + sorted(digits_left)[::-1]
		best = max([best, int(''.join(map(str, result)))])
	print(best)


def main():
	a = list(input(''))
	b = input('')
	a.sort()
	a.reverse()
	maxNumber = ''
	if len(a) < len(str(b)):
		for num in a:
			maxNumber += num
	else:
		maxNumber = fillInDigit(a, b, [], '')
	print(maxNumber)

def fillInDigit(num1, num2, usedDigits, currentMaxNumber):
	maxLeadingDigit = '-1'
	secondLeadingDigit = int(num2[0])
	for x in num1:
		if int(x) <= secondLeadingDigit and int(x) > int(maxLeadingDigit):
			maxLeadingDigit = x
	maxNumber1 = currentMaxNumber
	maxNumber1 += maxLeadingDigit
	usedDigits.append(maxLeadingDigit)
	num1.remove(maxLeadingDigit)
	num2 = num2[1:]
	if len(num1) == 0:
		return maxNumber1
	elif int(maxLeadingDigit) < secondLeadingDigit:
		if len(num1) > 0:
			for num in num1:
				maxNumber1 += num
		return maxNumber1
	elif int(min(num1)) > int(num2[0]):
		for i in range(len(maxNumber1) - 1, -1, -1):
			maxLeadingDigit2 = '-1'
			for x in num1:
				if int(x) < int(maxNumber1[i]) and int(x) > int(maxLeadingDigit2):
					maxLeadingDigit2 = x
			if maxLeadingDigit2 == '-1':
				num1.append(usedDigits[len(usedDigits) - 1])
				usedDigits.pop()
			else:
				num1.append(maxNumber1[i])
				maxNumber1 = maxNumber1[:i] + maxLeadingDigit2
				num1.remove(maxLeadingDigit2)
				num1.sort()
				num1.reverse()
				if len(num1) > 0:
					for num in num1:
						maxNumber1 += num
				return maxNumber1
	else:
		return fillInDigit(num1, num2, usedDigits, maxNumber1)
main()


s = input()
s1 = input()
l = []
l1 = []
for x in s:
	l.append(int(x))
for x in s1:
	l1.append(int(x))
d = {}
for x in l:
	d[x] = d.get(x, 0) + 1
f = False
if len(s1) > len(s):
	l = sorted(l)
	l = l[::-1]
	print(''.join(map(str, l)))
	exit()
ans = [0] * len(s)
ki = 0
i = 0
while i < len(l1):
	f = True
	for j in range(max(l1[i], ki), -1, -1):
		if d.get(j, -1) > 0:
			ans[i] = j
			d[j] -= 1
			f = False
			if j != l1[i]:
				ki = 9
			break
	if f:
		for i1 in range(i - 1, -1, -1):
			f1 = False
			for j in range(max(l1[i1], ki) - 1, -1, -1):
				if d.get(j, -1) > 0:
					d[ans[i1]] += 1
					ans[i1] = j
					d[j] -= 1
					f1 = True
					i = i1
					ki = 9
					break
			if f1:
				break
			else:
				d[ans[i1]] += 1
				ans[i1] = 0
	i += 1
print(''.join(map(str, ans)))


a = input()
b = input()
reva = sorted(list(a), reverse=True)
if len(a) < len(b):
	print(''.join(reva))
else:
	a_hash = [0] * 10
	a = int(a)
	while a > 0:
		a_hash[a % 10] += 1
		a = a // 10
	c = 0
	ans = []
	len_b = len(b)
	flag = 0
	flag1 = 0
	while c != len_b:
		temp = int(b[c])
		if flag == 1:
			temp -= 1
			flag = 0
		for i in range(temp, -1, -1):
			if a_hash[i] != 0:
				a_hash[i] -= 1
				ans.append(str(i))
				c += 1
				break
			if i == 0:
				x = ans.pop()
				a_hash[int(x)] += 1
				c -= 1
				flag = 1
				break
		if temp == -1:
			x = ans.pop()
			a_hash[int(x)] += 1
			c -= 1
			flag = 1
		for j in range(9, -1, -1):
			while a_hash[j] != 0:
				ans.append(str(j))
				a_hash[j] -= 1
		if int(b) >= int(''.join(ans)):
			break
		else:
			for i in range(c, len_b):
				a_hash[int(ans[i])] += 1
			ans = ans[:c]
	print(''.join(ans))


import sys
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def read():
	tc = 0
	if tc:
		input = sys.stdin.readline
	else:
		sys.stdin = open('input1.txt', 'r')
		sys.stdout = open('output1.txt', 'w')

def permute(b, x, ind):
	if ind == len(b):
		return 1
	f = 0
	for i in range(9, -1, -1):
		if x[i] > 0 and i <= int(b[ind]):
			x[i] -= 1
			ans[ind] = str(i)
			if i < int(b[ind]):
				f = 1
			if f:
				k = 9
				for j in range(ind + 1, len(b)):
					while x[k] == 0:
						k -= 1
					ans[j] = str(k)
					x[k] -= 1
				return 1
			if permute(b, x, ind + 1):
				return 1
			x[i] += 1
	return 0

def solve():
	a = ii()
	b = ii()
	if len(str(a)) < len(str(b)):
		s = list(str(a))
		s.sort(reverse=True)
		print(''.join(s))
	else:
		x = [0] * 10
		for i in str(a):
			x[int(i)] += 1
		b = str(b)
		i = 0
		global ans
		ans = [0] * len(b)
		permute(b, x, 0)
		print(''.join(ans))
solve()


a = sorted(input())
b = input()
ans = ''
a = a[::-1]
while a:
	for i in range(len(a)):
		c = a[:i] + a[i + 1:]
		d = ans + a[i] + ''.join(c[::-1])
		if int(d) <= int(b):
			ans += a[i]
			a = c
			break
print(ans)


a = list(input())
a = sorted(a)
a = a[::-1]
b = input()
if len(b) > len(a):
	print(''.join(a))

def highless(n):
	temp = '0'
	lesser = False
	for i in a:
		if i < n and i >= temp:
			temp = i
			lesser = True
	if lesser:
		return temp
	else:
		return -1
c = []
if len(a) == len(b):
	for i in range(len(a)):
		if b[i] in a:
			c.append(b[i])
			a.remove(b[i])
		else:
			val = highless(b[i])
			if val != -1:
				c.append(val)
				a.remove(val)
				c = c + sorted(a)[::-1]
				break
			else:
				while val == -1:
					last = c.pop()
					a.append(last)
					val = highless(last)
				c.append(val)
				a.remove(val)
				c = c + sorted(a)[::-1]
				break
	print(''.join(c))


mass = list(input())
b = int(input())
mass.sort()
mass = mass[::-1]
p = ''
while len(mass) > 0:
	for i in range(len(mass)):
		n = p + mass[i] + ''.join(sorted(mass[:i] + mass[i + 1:]))
		if int(n) <= b:
			p += mass[i]
			mass = mass[:i] + mass[i + 1:]
			break
print(p)


import sys
a = sys.stdin.readline().strip()
b = sys.stdin.readline().strip()
dict_ = dict()
for i in range(10):
	dict_[i] = 0
for a_ in a:
	dict_[int(a_)] += 1
diff = len(b) - len(a)
if diff > 0:
	print(''.join(sorted(a, reverse=True)))
else:
	pos = 0
	result = ''
	limit = -1
	while pos < len(a):
		cur_symbol = b[pos]
		prev_symbol = -1
		max_val = int(cur_symbol)
		if pos > 0:
			prev_symbol = b[pos - 1]
			prev_result_symbol = result[pos - 1]
			if result[:pos] < b[:pos]:
				max_val = 9
		appended_symbol = -1
		for i in range(max_val, -1, -1):
			if dict_[i] > 0:
				if limit < 0 or (limit > 0 and i < limit):
					appended_symbol = i
					break
		limit = -1
		if appended_symbol >= 0:
			pos += 1
			result += str(appended_symbol)
			dict_[i] -= 1
		else:
			pos -= 1
			limit = int(result[-1])
			dict_[limit] += 1
			result = result[:-1]
	print(result)


import sys

def backtrack(sol, remaining, b, pos, free):
	if len(sol) == len(b):
		print(sol)
		sys.exit(0)
	for c in '9876543210':
		if not free and c > b[pos]:
			continue
		if not remaining[ord(c) - ord('0')]:
			continue
		remaining[ord(c) - ord('0')] -= 1
		backtrack(sol + c, remaining, b, pos + 1, free or c < b[pos])
		remaining[ord(c) - ord('0')] += 1
a = ''.join(sorted(input())[::-1])
b = input()
if len(a) < len(b):
	print(a)
else:
	x = [0] * 10
	for c in a:
		x[ord(c) - ord('0')] += 1
	backtrack('', x, b, 0, False)


def smallest(d):
	out = ''
	for j in range(0, 10):
		out += '%d' % j * d[j]
	return out

def largest(d):
	out = ''
	for j in range(9, -1, -1):
		out += '%d' % j * d[j]
	return out
sa = input()
sb = input()
b = int(sb)
h = int(sa)
digits_a = [0] * 10
while h > 0:
	digits_a[h % 10] += 1
	h //= 10
out = ''
if len(sb) > len(sa):
	print(largest(digits_a))
	exit()
out = 0
for i in range(len(sa) - 1, -1, -1):
	for j in range(9, -1, -1):
		if digits_a[j] == 0:
			continue
		if j < b % 10 ** (i + 1) // 10 ** i:
			digits_a[j] -= 1
			if out > 0:
				print('{}{}{}'.format(out, j, largest(digits_a)))
				exit()
			else:
				print('{}{}'.format(j, largest(digits_a)))
				exit()
		if j == b % 10 ** (i + 1) // 10 ** i:
			if i == 0:
				out = 10 * out + j
				print(out)
				exit()
			digits_a[j] -= 1
			if int(smallest(digits_a)) <= b % 10 ** i:
				out = 10 * out + j
				break
			else:
				digits_a[j] += 1
print(out)


def dig(d):
	return ord(d) - ord('0')

def biggest_left(counts):
	res = ''
	for i in range(9, -1, -1):
		res += str(i) * counts[i]
	return res

def ok(d, _counts, rest):
	if rest == '':
		return True
	counts = _counts.copy()
	counts[d] -= 1
	r = ''
	for i in range(10):
		r += str(i) * counts[i]
	return int(r) <= int(rest)

def main():
	(a, b) = (input(), input())
	counts = [0] * 10
	for d in a:
		counts[dig(d)] += 1
	ans = ''
	if len(a) < len(b):
		print(biggest_left(counts))
		return
	n = len(a)
	for i in range(n):
		d = dig(b[i])
		if counts[d] and ok(d, counts, b[i + 1:]):
			ans += b[i]
			counts[d] -= 1
		else:
			for s in range(d - 1, -1, -1):
				if counts[s] > 0:
					ans += str(s)
					counts[s] -= 1
					ans += biggest_left(counts)
					print(ans)
					return
	print(ans)
main()


a = input().strip()
b = input().strip()
if len(b) > len(a):
	print(''.join(sorted(a))[::-1])
else:
	f = [0] * 11
	for ele in a:
		f[int(ele)] += 1
	ans = ''
	i = 0
	n = len(b)
	while i < n:
		num = int(b[i])
		if f[num]:
			ans += str(num)
			f[num] -= 1
		else:
			break
		i += 1
	flag = 0
	while True and len(ans) != len(a):
		num = int(b[i])
		num -= 1
		while num >= 0:
			if f[num]:
				ans += str(num)
				f[num] -= 1
				for j in range(9, -1, -1):
					ans += str(j) * f[j]
				break
			num -= 1
		if len(ans) == len(a):
			break
		f[int(ans[-1])] += 1
		ans = ans[:-1]
		i -= 1
	print(ans.strip())


import sys
a = sys.stdin.readline().split()[0]
b = sys.stdin.readline().split()[0]
a = [int(x) for x in a]
b = [int(x) for x in b]

def mov(a, x1, x2):
	a.insert(x1, a.pop(x2))
	return a

def min(a):
	m = 9
	for i in a:
		x = int(i)
		if x < m:
			m = x
	return m

def max(a):
	m = 0
	for i in a:
		x = int(i)
		if x > m:
			m = x
	return m

def maxb(a, b):
	m = -1
	for i in a:
		x = int(i)
		if x > m and x < b:
			m = x
	return m

def ens(a):
	f = [x for x in a[:i + 1]]
	d = [x for x in a[i + 1:]]
	d.sort()
	d.reverse()
	f.extend(d)
	return f

def f(i, l):
	global a
	global b
	global e
	global t
	global w
	if e == 0:
		return 0
	if i == l:
		if a[i] < b[i]:
			return a
		else:
			e = 0
			return -1
	if a[i] != b[i]:
		x = -1
		if b[i] in a[i:]:
			if t == 0:
				w += 1
			x = b[i]
			mov(a, i, i + a[i:].index(x))
		elif maxb(a[i + 0:], b[i]) in a[i + 0:]:
			t = 1
			x = maxb(a[i + 0:], b[i])
			mov(a, i, i + a[i:].index(x))
			a = ens(a)
			return 2
		else:
			e = 0
			return 0
	elif t == 0:
		w += 1
	return 1
t = 0
w = 0
e = 1
a1 = [x for x in a]
b1 = [x for x in b]
a1.sort()
b1.sort()
if a1 == b1:
	c1 = int(''.join([str(x) for x in b]))
	print(c1)
else:
	if len(a) == len(b):
		for i in range(len(a)):
			q = f(i, len(a))
			if q == 2:
				r = 2
				break
			if q == 0:
				break
			if q == -1:
				q = 2
				break
		if q != 2:
			r = 0
			for i in range(w + 0, -1, -1):
				if i > len(a) - 1:
					break
				if a[i] < b[i]:
					a = ens(a)
					r = 1
					break
				if maxb(a[i + 1:], b[i]) in a[i + 1:]:
					x = maxb(a[i + 1:], b[i])
					mov(a, i, i + a[i:].index(x))
					a = ens(a)
					r = 1
					break
	else:
		a.sort()
		a.reverse()
	c1 = int(''.join([str(x) for x in a]))
	print(c1)


success = 0

def solve(b, freq, i, n, res):
	global success
	if i == len(b):
		success = res
	else:
		success = 0
		move = 9
		while move >= 0 and success == 0:
			m = int(b[i])
			if freq[move] > 0 and res * 10 + move <= n * 10 + m:
				res = res * 10 + move
				n = n * 10 + m
				freq[move] -= 1
				if solve(b, freq, i + 1, n, res) == 0:
					res //= 10
					n //= 10
					freq[move] += 1
			move -= 1
	return success
a = input()
b = input()
freq = []
for i in range(10):
	freq.append(0)
v = []
for x in a:
	n = int(x)
	v.append(n)
	freq[n] += 1
v.sort()
ans = 0
if len(b) > len(a):
	m = 1
	for x in v:
		ans = x * m + ans
		m *= 10
else:
	ans = solve(b, freq, 0, 0, 0)
print(ans)


(n, N) = (input(), input())
N = [i for i in N]
n = sorted((i for i in n), reverse=True)

def has_hal(n, N):
	return sorted(n) <= N

def solve(n, N):
	if len(n) < len(N):
		return ''.join(n)
	if not n:
		return ''
	for (pos, d) in enumerate(n):
		if d > N[0]:
			continue
		if d == N[0]:
			n1 = n[:]
			n1.remove(d)
			if has_hal(n1, N[1:]):
				return d + solve(n1, N[1:])
		if d < N[0]:
			n1 = n[:pos] + n[pos + 1:]
			return d + ''.join(n1)
print(solve(n, N))


def possible(a, index, a1, b):
	rem = []
	for i in range(len(a)):
		if i != index:
			rem.append(a[i])
	a3 = a1[:]
	rem.sort()
	a3.append(a[index])
	a3.extend(rem)
	a2 = ''
	for i in a3:
		a2 += str(i)
	if int(a2) <= b:
		return True
	return False

def main():
	a = list(map(int, input()))
	b = int(input())
	a.sort(reverse=True)
	a1 = []
	for pos in range(len(a)):
		for i in range(len(a)):
			if possible(a, i, a1, b):
				a1.append(a[i])
				a.pop(i)
				break
	for i in a1:
		print(i, end='')
main()


a = sorted(input())[::-1]
b = input()
n = len(b)
if len(a) < n:
	s = ''.join(a)
else:
	s = ''
	while a:
		i = 0
		while s + a[i] + ''.join((a[:i] + a[i + 1:])[::-1]) > b:
			i += 1
		s += a.pop(i)
print(s)


import sys
import math

def rec(i, n, l):
	if i == n:
		return []
	else:
		x = l2[i]
		flag = 0
		o = []
		p = []
		mi = -1
		for j in l:
			if j < x:
				if j > mi:
					if i == 0 and j == 0:
						o.append(j)
						p.append(j)
						continue
					mi = j
			if x == j:
				flag = 1
			o.append(j)
			p.append(j)
		if flag:
			o.remove(x)
		if mi == -1 and flag == 0:
			return []
		ans1 = []
		if flag:
			ans1 = [x] + rec(i + 1, n, o)
		if mi != -1:
			p.remove(mi)
		p.sort(reverse=True)
		ans2 = [mi] + p
		if len(ans1) == n - i:
			return ans1
		else:
			return ans2
for _ in range(1):
	a = int(input())
	b = int(input())
	e1 = str(a)
	e2 = str(b)
	l1 = []
	l2 = []
	for i in e1:
		l1.append(int(i))
	for i in e2:
		l2.append(int(i))
	if len(l1) < len(l2):
		l1.sort(reverse=True)
		o = []
		for i in l1:
			o.append(str(i))
		print(''.join(o))
	else:
		n = len(l2)
		ans = rec(0, n, l1)
		w = []
		for i in ans:
			w.append(str(i))
		print(''.join(w))


(a, b) = (sorted(input()), int(input()))
for i in range(len(a)):
	for j in range(i + 1, len(a)):
		c = int(str.join('', a))
		(a[i], a[j]) = (a[j], a[i])
		d = int(str.join('', a))
		if c <= d <= b:
			continue
		else:
			(a[i], a[j]) = (a[j], a[i])
print(str.join('', a))


def dfs(b, bid, a, used, ans, n_used):
	if n_used == len(a):
		if int(ans) <= int(b):
			return ans
		else:
			return None
	used_x = set()
	for (i, x) in enumerate(a):
		if not used[i] and int(ans + str(x)) <= int(b[:bid + 1]) and (x not in used_x):
			used_x.add(x)
			if x == int(b[bid]):
				ans += str(x)
				used[i] = True
				r = dfs(b, bid + 1, a, used, ans, n_used + 1)
				if r is not None:
					return r
				used[i] = False
				ans = ans[:-1]
			else:
				used[i] = True
				ans += str(x)
				for (ii, xx) in enumerate(a):
					if not used[ii]:
						ans += str(xx)
				return ans
	return None

def main():
	a = input()
	b = input()
	a_s = int(''.join(sorted(a, reverse=True)))
	if a_s <= int(b):
		print(a_s)
		return
	a = list(map(int, sorted(a, reverse=True)))
	used = [False] * len(a)
	ans = ''
	ans = dfs(b, 0, a, used, ans, 0)
	print(ans)
main()


def main():
	s = list(input())
	t = list(input())
	if len(s) < len(t):
		s.sort(reverse=True)
		print(''.join(s))
	else:
		count = [0] * 10
		for elm in s:
			count[ord(elm) - ord('0')] += 1
		ans = []
		less = False
		for i in range(len(s)):
			for j in range(9, -1, -1):
				if not less:
					if j <= ord(t[i]) - ord('0') and count[j] > 0:
						if j < ord(t[i]) - ord('0'):
							ans.append(chr(j + ord('0')))
							count[j] -= 1
							less = True
							break
						else:
							curr_num = 0
							for k in range(10):
								if j == k:
									for tmp in range(count[k] - 1):
										curr_num = curr_num * 10 + k
								else:
									for tmp in range(count[k]):
										curr_num = curr_num * 10 + k
							rest_num = 0
							for k in range(i + 1, len(s)):
								rest_num = rest_num * 10 + (ord(t[k]) - ord('0'))
							if rest_num >= curr_num:
								ans.append(chr(j + ord('0')))
								count[j] -= 1
								break
							else:
								continue
				elif count[j] > 0:
					ans.append(chr(j + ord('0')))
					count[j] -= 1
					break
		print(''.join(ans))
main()


a = input()
b = input()
if len(a) < len(b):
	print(''.join(sorted(list(a), reverse=True)))
else:
	lst = sorted(list(a), reverse=True)
	temp = ''
	prefix = ''
	while len(lst) > 0:
		for x in range(len(lst)):
			temp = prefix + lst[x] + ''.join(sorted(lst[:x] + lst[x + 1:]))
			if temp <= b:
				prefix = prefix + lst[x]
				lst.remove(lst[x])
				break
	print(prefix)


a = input()
b = input()
a_cifr = [0] * 10
for i in a:
	a_cifr[int(i)] += 1
if len(b) > len(a):
	cur = list(a)
	cur.sort(reverse=True)
	for i in cur:
		print(i, end='')
	exit(0)

def vniz():
	cur = ''
	for i in range(0, 10):
		cur += str(i) * a_cifr[i]
	return cur
abba = 123

def boba():
	abbaa = 12
	abbaa += abba

def vverh():
	cur = ''
	for i in range(9, -1, -1):
		cur += str(i) * a_cifr[i]
	return cur
full = ''
for i in range(len(b)):
	cur = int(b[i]) + 2
	cur -= 2
	if a_cifr[cur] > 0:
		a_cifr[cur] -= 1
		cur1 = int(full + b[i] + vniz())
		if cur1 <= int(b):
			full += str(b[i])
			continue
		else:
			a_cifr[cur] += 1
			for j in range(cur - 1, -1, -1):
				if a_cifr[j]:
					a_cifr[j] -= 1
					print(full + str(j) + vverh())
					exit(0)
	else:
		for j in range(cur - 1, -1, -1):
			if a_cifr[j]:
				a_cifr[j] -= 1
				print(full + str(j) + vverh())
				exit(0)
print(full)


import os, math
from sys import stdin, stdout
A = []
l = 0
ma = 0
hi = 0

def foo(req, P, d):
	global A, l, hi
	if d >= l:
		if req <= hi:
			return req
		return
	x = int(P[d])
	val = req
	ans = 0
	if sum(A[:x + 1]) == 0:
		B = list(A)
		for k in range(9, -1, -1):
			while B[k]:
				req *= 10
				req += k
				B[k] -= 1
		if req <= hi:
			ans = max(ans, req)
		return ans
	else:
		j = x - 1
		while j >= 0 and A[j] == 0:
			j -= 1
		if j > -1:
			A[j] -= 1
			req *= 10
			req += j
			B = list(A)
			for k in range(9, -1, -1):
				while B[k]:
					req *= 10
					req += k
					B[k] -= 1
			if req <= hi:
				ans = max(ans, req)
			A[j] += 1
		req = val
		if A[x] == 0:
			return ans
		else:
			req *= 10
			req += x
			A[x] -= 1
			ans = max(ans, foo(req, P, d + 1))
			A[x] += 1
			return ans

def main():
	global A, l, ma, hi
	ten = [10 ** i for i in range(0, 20)]
	x = stdin.readline()
	y = stdin.readline()
	if len(y) > len(x):
		A = sorted([int(i) for i in x[:-1]], reverse=True)
		A = map(str, A)
		print(''.join(A))
		return
	x = x[:-1]
	y = y[:-1]
	l = len(x)
	A = [0] * 10
	hi = int(y)
	ma = -1
	for i in x:
		A[int(i)] += 1
	ma = foo(0, y, 0)
	print(ma)
main()


a = sorted(input())
b = int(input())
a = a[::-1]
prefix = ''
while a:
	for i in range(len(a)):
		n = prefix + a[i] + ''.join(sorted(a[:i] + a[i + 1:]))
		if int(n) <= b:
			prefix += a[i]
			a.pop(i)
			break
print(prefix)


a = input()
b = input()
acnt = [0] * 10
ans = []
for i in range(len(a)):
	acnt[int(a[i])] += 1
if len(a) < len(b):
	for i in range(9, -1, -1):
		while acnt[i] > 0:
			ans.append(i)
			acnt[i] -= 1
else:
	for i in range(len(a)):
		f = 1
		for j in range(9, -1, -1):
			if j <= int(b[i]) and acnt[j] > 0:
				acnt[j] -= 1
				ans.append(j)
				f = 0
				break
		if f:
			while f:
				acnt[ans.pop()] += 1
				for j in range(9, -1, -1):
					if j < int(b[len(b) - sum(acnt)]) and acnt[j] > 0:
						ans.append(j)
						acnt[j] -= 1
						f = 0
						break
			for i in range(9, -1, -1):
				while acnt[i] > 0:
					ans.append(i)
					acnt[i] -= 1
			break
		if j < int(b[i]):
			for i in range(9, -1, -1):
				while acnt[i] > 0:
					ans.append(i)
					acnt[i] -= 1
			break
print(''.join(map(str, ans)))


from collections import Counter

def max_num(a, b):
	if len(b) > len(a):
		val = ''.join(sorted(a, reverse=True))
		return int(val)
	else:
		res = ''
		for i in b:
			if i in a:
				a.remove(i)
				if ''.join(b[len(res) + 1:]) >= ''.join(sorted(a)):
					res += i
				else:
					a.append(i)
					break
			else:
				break
		new_b = b[len(res):]
		if new_b == []:
			return res
		for i in new_b:
			for j in range(int(i) - 1, -1, -1):
				if str(j) in a:
					a.remove(str(j))
					return res + str(j) + ''.join(sorted(a, reverse=True))
a = list(input())
b = list(input())
print(max_num(a, b))


a = list(input())
b = list(input())
a = list(reversed(sorted(a)))
if len(a) < len(b):
	print(''.join(a))
	exit()

def rec(a, b, k):
	if k == len(a):
		return ''
	if b[k] in a:
		for i in range(len(a)):
			if a[i] == b[k]:
				a[i] = ''
				break
		tmp = rec(a, b, k + 1)
		if tmp != -1:
			return b[k] + tmp
		a[i] = b[k]
	tmp = max(filter(lambda x: x < b[k], a))
	if not tmp <= '9' or not tmp >= '0':
		return -1
	for i in range(len(a)):
		if a[i] == tmp:
			a[i] = ''
			break
	return tmp + ''.join(a)
print(rec(a, b, 0))


import copy
a = input()
b = int(input())
digits = [int(x) for x in list(str(a))]
digits.sort(reverse=True)

def search(num, digits):
	global b
	s = set()
	for i in range(len(digits)):
		if digits[i] not in s:
			s.add(digits[i])
			if int(num + str(digits[i]) + '0' * (len(digits) - 1)) <= b:
				digits2 = digits.copy()
				del digits2[i]
				if len(digits2) == 0:
					return num + str(digits[i])
				res = search(num + str(digits[i]), digits2)
				if res != False:
					return res
	return False
print(search('', digits))


R = lambda : map(int, input().split())
a = sorted(map(int, input()))
b = list(map(int, input()))
bn = int(''.join(map(str, b)))
res = int(''.join(map(str, sorted(a))))
if len(b) != len(a):
	print(''.join(map(str, sorted(a, reverse=True))))
else:
	for i in range(len(a)):
		for j in range(i + 1, len(a)):
			if a[i] < a[j] < b[i]:
				(a[i], a[j]) = (a[j], a[i])
		tmp = int(''.join(map(str, a[:i + 1] + sorted(a[i + 1:], reverse=True))))
		res = max(res, tmp) if tmp <= bn else res
		for j in range(i + 1, len(a)):
			if a[j] == b[i]:
				(a[i], a[j]) = (a[j], a[i])
	print(res)


a = [ord(e) - ord('0') for e in list(input().strip())]
b = [ord(e) - ord('0') for e in list(input().strip())]
a.sort(reverse=True)
h = [0 for i in range(10)]
for x in a:
	h[x] += 1
if len(a) < len(b):
	print(''.join(map(str, a)))
	exit(0)

def gmax(hx):
	s = list(hx)
	res = list()
	for i in range(9, -1, -1):
		while s[i] > 0:
			res.append(i)
			s[i] -= 1
	return res

def gmin(hx):
	s = list(hx)
	res = list()
	for i in range(10):
		while s[i] > 0:
			res.append(i)
			s[i] -= 1
	return res
res = list()

def finalize(x):
	for y in range(x - 1, -1, -1):
		if h[y] > 0:
			res.append(y)
			h[y] -= 1
			for i in range(9, -1, -1):
				while h[i] > 0:
					res.append(i)
					h[i] -= 1
			return
p = 0
while p < len(a):
	x = b[p]
	if h[x] > 0:
		hh = list(h)
		hh[x] -= 1
		if b[p + 1:] >= gmin(hh):
			res.append(x)
			h[x] -= 1
		else:
			finalize(x)
			break
	else:
		finalize(x)
		break
	p += 1
print(''.join(map(str, res)))


def search(current, digits, target, idx, bulk):
	if len(current) == len(target) and int(current) <= int(target):
		print(current)
		exit(0)
	possibilities = [char for char in digits if bulk or (char <= target[idx] and char in digits)]
	if len(possibilities) == 0:
		return None
	for possible_digit in sorted(set(possibilities), reverse=True):
		tmp_digits = list(digits)
		tmp_digits.remove(possible_digit)
		if not bulk:
			bulk = True if possible_digit != target[idx] else False
		search(current + possible_digit, tmp_digits, target, idx + 1, bulk)

def main():
	digits = sorted(list(input()), reverse=True)
	target = input()
	if len(digits) < len(target):
		print(''.join(digits))
		exit(0)
	entries = [char for char in digits if char <= target[0]]
	for current in sorted(set(entries), reverse=True):
		tmp_digits = list(digits)
		tmp_digits.remove(current)
		search(current, tmp_digits, target, 1, True if current != target[0] else False)
main()


f = 0
res = []

def rec(c, b, pos):
	global f
	global res
	if f == 1:
		return
	if pos == len(b):
		print(''.join(res))
		f = 1
		return
	if pos != 0:
		for i in range(int(b[pos]), -1, -1):
			if c[i] != 0 and f == 0:
				if i < int(b[pos]):
					q = str(i)
					c[i] -= 1
					for i in range(len(c) - 1, -1, -1):
						q += str(i) * c[i]
					print(''.join(res), q, sep='')
					f = 1
					return
				c[i] -= 1
				res.append(str(i))
				rec(c, b, pos + 1)
				res = res[:-1]
				c[i] += 1
	else:
		for i in range(int(b[pos]), 0, -1):
			if c[i] != 0 and f == 0:
				if i < int(b[pos]):
					q = str(i)
					c[i] -= 1
					for i in range(len(c) - 1, -1, -1):
						q += str(i) * c[i]
					print(''.join(res), q, sep='')
					f = 1
					return
				c[i] -= 1
				res.append(str(i))
				rec(c, b, pos + 1)
				res = res[:-1]
				c[i] += 1
a = [x for x in input()]
b = [x for x in input()]
if len(b) > len(a):
	print(''.join(sorted(a, key=lambda x: -int(x))))
else:
	c = [0 for x in range(10)]
	for i in a:
		c[int(i)] += 1
	rec(c, b, 0)


def poss(a2, b):
	if a2 == []:
		return True
	a2.sort()
	a2 = map(str, a2)
	s = ''
	for i in a2:
		s += i
	s = int(s)
	b = int(b)
	if s <= b:
		return True
	return False

def abc(a2, b, less=False):
	if a2 == []:
		return ''
	if less:
		a2.sort(reverse=True)
		s = ''
		for i in a2:
			s += str(i)
		return s
	max1 = min(a2)
	flag = True
	b = str(b)
	for i in range(len(a2)):
		if int(b[0]) == a2[i] and flag:
			if less or poss(a2[:i] + a2[i + 1:], b[1:]):
				return str(a2[i]) + abc(a2[:i] + a2[i + 1:], b[1:], less)
			else:
				flag = False
		if a2[i] < int(b[0]):
			max1 = max(max1, a2[i])
	a2.remove(max1)
	return str(max1) + abc(a2, b[1:], True)
a = list(map(int, list(input())))
b = input()
if len(b) <= len(a):
	print(abc(a, b))
else:
	print(abc(a, b, True))


from collections import Counter
(a, b) = (input(), input())
if len(a) < len(b):
	print(''.join(sorted(a)[::-1]))
else:
	a = Counter(a)
	t = []
	for q in b:
		t.append(q)
		a[q] -= 1
		if a[q] < 0:
			break
	else:
		print(''.join(t))
		return
	s = ''
	while not s:
		d = t.pop()
		a[d] += 1
		for (q, k) in a.items():
			if k > 0 and s < q < d:
				s = q
	a[s] -= 1
	t.append(s)
	for q in '9876543210':
		t += [q] * a[q]
	print(''.join(t))


def check(m):
	nonlocal c, ans
	ans = [0] * len(a)
	have = c[:]
	for i in range(m):
		if have[b[i]] > 0:
			have[b[i]] -= 1
			ans[i] = b[i]
		else:
			return 0
	for i in range(b[m] - 1, -1, -1):
		if have[i]:
			ans[m] = i
			have[i] -= 1
			break
	else:
		return 0
	j = m + 1
	for i in range(10, -1, -1):
		for t in range(have[i]):
			ans[j] = i
			j += 1
	return j == len(a)
a = list(map(int, list(input())))
b = list(map(int, list(input())))
ans = [0] * len(a)
if len(a) < len(b):
	a.sort(reverse=1)
	for i in a:
		print(i, end='')
	print()
else:
	a.sort(reverse=1)
	if a == sorted(b, reverse=1):
		for i in b:
			print(i, end='')
		print()
	else:
		c = [0] * 15
		for i in a:
			c[i] += 1
		for i in range(len(a) - 1, -1, -1):
			if check(i):
				for i in ans:
					print(i, end='')
				print()
				break
		else:
			for i in b:
				print(i, end='')
			print()


def main():
	num = input()
	maxi = int(input())
	nl = len(num)
	maxNum = 0
	nums = list(num)
	for x in range(len(nums)):
		nums[x] = int(nums[x])
	nums.sort()
	nums = nums[::-1]
	if int(str(maxi)[0]) in nums and len(str(maxi)) == len(nums):
		nums.remove(int(str(maxi)[0]))
		maxNum = recur(int(str(maxi)[0]), nums, maxi)
		nums.append(int(str(maxi)[0]))
		nums.sort(reverse=True)
	elif len(str(maxi)) > len(nums):
		for x in nums:
			maxNum = maxNum * 10 + x
	if maxNum == 0 or maxNum > maxi:
		maxNum = 0
		maxD = int(str(maxi)[0])
		a = 0
		for x in nums:
			if x < maxD:
				a = max(x, a)
		maxNum = a
		nums.remove(a)
		for x in nums:
			maxNum = maxNum * 10 + x
		nums.append(a)
		nums.sort(reverse=True)
	print(maxNum)

def recur(curr, poss, maxi):
	maxNum = 0
	if len(poss) == 0:
		return curr
	if int(str(maxi)[len(str(curr))]) in poss:
		poss.remove(int(str(maxi)[len(str(curr))]))
		maxNum = recur(curr * 10 + int(str(maxi)[len(str(curr))]), poss.copy(), maxi)
		poss.append(int(str(maxi)[len(str(curr))]))
		poss.sort(reverse=True)
	if maxNum > maxi or maxNum == 0:
		maxD = int(str(maxi)[len(str(curr))])
		a = 0
		for x in poss:
			if x < maxD:
				a = max(x, a)
		if a not in poss:
			return maxi + 5
		curr = curr * 10 + a
		poss.remove(a)
		for x in poss:
			curr = curr * 10 + x
		poss.append(maxD)
		poss.sort(reverse=True)
		return curr
	else:
		return maxNum
main()


import random
b = set()

def foo(sa, na, cbb, d, uuid):
	if hash(str(sa) + str(cbb)) in b:
		return ('', 0)
	else:
		b.add(hash(str(sa) + str(cbb)))
	for i in sa:
		if i <= na[0] or cbb:
			sac = sa.copy()
			sac.remove(i)
			(r, s) = foo(sac, na[1:], cbb or i < na[0], d + 1, uuid + [random.randint(0, 100)])
			if s:
				return (str(i) + r, 1)
	return ('', len(sa) == 0)
s = sorted(map(int, input()), reverse=1)
n = list(map(int, input()))
if len(n) > len(s):
	n = [9] * len(s)
print(foo(s, n, 0, 1, [0])[0])


def split(integer):
	ret = []
	while integer != 0:
		ret.append(integer % 10)
		integer //= 10
	return ret[::-1]

def combine(lst):
	total = 0
	n = len(lst)
	for i in range(n):
		total += 10 ** (n - i - 1) * lst[i]
	return int(total)

def solve3(a, b):
	al = sorted(list(split(a)))[::-1]
	bl = list(split(b))
	if len(bl) > len(al):
		print(combine(al))
		return
	if a == b:
		print(a)
		return
	ptr = 0
	n = len(al)
	while ptr < n:
		val = bl[ptr]
		selection = al[ptr]
		if selection > val:
			k = al.pop(ptr)
			al.append(k)
		if selection == val:
			if ptr == n - 1:
				print(combine(al))
				break
			elif combine(sorted(al[ptr + 1:])) > combine(bl[ptr + 1:]):
				k = al.pop(ptr)
				al.append(k)
			else:
				ptr += 1
				al = al[:ptr] + sorted(al[ptr:])[::-1]
		if selection < val:
			print(combine(al[:ptr + 1] + list(sorted(al[ptr + 1:])[::-1])))
			break
a = int(input())
b = int(input())
solve3(a, b)


a = input()
b = int(input())
lnb = len(str(b))
l = len(a)
if int(a) == b:
	print(a)
	exit(0)
if lnb > l:
	print(''.join(reversed(sorted(a))))
	exit(0)
dig = [0] * 10
for i in a:
	dig[int(i)] += 1
k = 0
s = ''
while len(s) != l:
	while k < 100:
		for j in range(9, -1, -1):
			if not dig[j]:
				continue
			dig[j] -= 1
			if int(s + str(j) + ''.join([str(i) * dig[i] for i in range(10) if dig[i]])) <= b:
				s += str(j)
				break
			else:
				dig[j] += 1
		k += 1
print(s)


from collections import Counter
a = int(input())
b = int(input())

def sorted_diff(a, b):
	counter = Counter(list(str(b)))
	counter -= Counter(list(str(a)))
	result = []
	for key in sorted(counter.keys()):
		for i in range(counter[key]):
			result.append(key)
	return result
max_prefix = ''
for length in range(len(str(a))):
	diff = sorted_diff(max_prefix, a)
	max_curr = new_symb = None
	for symb in diff:
		diff_diff = sorted_diff(symb, ''.join(diff))
		next_prefix = int('{}{}{}'.format(max_prefix, symb, ''.join(diff_diff)))
		if next_prefix <= b:
			if max_curr is None:
				max_curr = next_prefix
				new_symb = symb
			elif max_curr < next_prefix:
				max_curr = next_prefix
				new_symb = symb
	max_prefix += new_symb
print(max_prefix)


a = sorted(list(input()))
b = int(input())
for i in range(len(a)):
	for j in range(len(a) - 1, -1, -1):
		num = a[:i] + a[j:j + 1] + a[i:j] + a[j + 1:]
		if int(''.join(num)) <= b:
			a = num
			break
print(''.join(a))


a = list(input())
b = input()
a.sort(reverse=True)
a = ''.join(a)
if int(a) < int(b):
	print(a)
	exit(0)
a = list(a)
bb = list(b)
b = int(b)
n = len(a)

def work(x, aa, res):
	if x == n - 1:
		if aa[0] <= bb[n - 1]:
			print(res * 10 + ord(aa[0]) - 48)
			exit(0)
		return
	for i in range(0, n - x):
		if i > 0 and aa[i] == aa[i - 1]:
			continue
		if aa[i] == bb[x]:
			tmp = aa[0:i]
			tmp.extend(aa[i + 1:n])
			work(x + 1, tmp, res * 10 + ord(aa[i]) - 48)
		elif aa[i] < bb[x]:
			res = res * 10 + ord(aa[i]) - 48
			for j in range(len(aa)):
				if i != j:
					res = res * 10 + ord(aa[j]) - 48
			print(res)
			exit(0)
print(work(0, a, 0))


a = int(input())
b = int(input())
l = []
while a != 0:
	d = a % 10
	a //= 10
	l.append(d)

def f(a, b):
	s = len(l)
	if s == 0:
		return a
	for i in range(len(l) - 1, -1, -1):
		min_suf = 0
		for j in range(len(l)):
			if j == i:
				continue
			min_suf *= 10
			min_suf += l[j]
		if a * 10 ** s + l[i] * 10 ** (s - 1) + min_suf <= b:
			dig = l.pop(i)
			return f(a * 10 + dig, b)
l.sort()
print(f(0, b))


a = input()
b = input()
a = ''.join(reversed(sorted(a)))
if len(a) < len(b):
	print(a)
else:
	ans = ''
	for i in range(len(b)):
		c = min((x for x in a))
		for x in a:
			if c < x <= b[i]:
				c = x
		if c > b[i]:
			j = i
			while c >= b[j]:
				c = ans[-1]
				a = a + c
				ans = ans[:len(ans) - 1]
				c = min((x for x in a))
				j -= 1
			c = min((x for x in a))
			a = ''.join(reversed(sorted(a)))
			for x in a:
				if c < x < b[j]:
					c = x
			i = j
		ans += c
		p = a.index(c)
		a = f'{a[:p]}{a[p + 1:]}'
		if c < b[i]:
			for j in range(len(a)):
				ans += a[j]
			break
	print(ans)


def get_smallest(m, l):
	res = ''
	for i in '0123456789':
		if m.get(i, 0):
			if i == l:
				res += i * (m[i] - 1)
			else:
				res += i * m[i]
	return res
a = input()
b = input()
if len(a) < len(b):
	a = sorted(a)
	a.reverse()
	print(''.join(a))
elif a == b:
	print(a)
else:
	cmap = dict()
	for i in a:
		cmap[i] = cmap.get(i, 0) + 1
	cur = 0
	res = ''
	gm = False
	while cur < len(a):
		for i in '9876543210':
			if cmap.get(i, 0):
				if cur == len(a) - 1 or i < b[cur] or gm:
					res += i
					cmap[i] -= 1
					gm = True
					break
				elif i == b[cur]:
					if get_smallest(cmap, i) <= b[cur + 1:]:
						res += i
						cmap[i] -= 1
						break
		cur += 1
	print(res)


def find_f(la, max_f):
	f = max_f
	while not la.count(f) and f >= 0:
		f -= 1
	return f

def get_ans():
	i = 0
	la_ = la[:]
	lb_ = lb[:]
	ans.clear()
	while i < len(a):
		f = find_f(la_, lb_[i])
		if f >= 0:
			la_.remove(f)
			ans.append(f)
			if f < lb_[i]:
				for j in range(i + 1, len(lb_)):
					lb_[j] = 9
			i += 1
		else:
			return i
	return -1
a = input()
b = input()
ans = []
la = list(map(int, list(a)))
lb = list(map(int, list(b)))
if len(a) < len(b):
	lb = [9] * len(b)
res = get_ans()
while res != -1:
	while lb[res - 1] == 0:
		res -= 1
	lb[res - 1] -= 1
	for j in range(res, len(lb)):
		lb[j] = 9
	res = get_ans()
print(''.join(map(str, ans)))


a = list(map(int, list(input())))
b = list(map(int, list(input())))
ch = False
p = []
a.sort()
a = a[::-1]
if len(b) > len(a):
	print(''.join(map(str, a)))
else:
	for i in range(len(b)):
		if b[i] in a:
			p.append(a.pop(a.index(b[i])))
		else:
			for x in a:
				if x < b[i]:
					p.append(a.pop(a.index(x)))
					break
			else:
				for z in p[::-1]:
					if a[-1] < z:
						i = -2
						while i >= -len(a) and a[i] < z:
							i -= 1
						el = a.pop(i + 1)
						a.extend(p[len(p) - p[::-1].index(z) - 1:])
						p = p[:len(p) - p[::-1].index(z) - 1] + [el]
						break
					a.append(p.pop(-1))
					a.sort()
					a = a[::-1]
			a.sort()
			a = a[::-1]
			p.extend(a)
			break
	print(''.join(map(str, p)))


a = input()
b = input()
if len(b) > len(a):
	l = [int(i) for i in a]
	l.sort()
	l = l[::-1]
	temp = [str(i) for i in l]
	s = ''.join(temp)
	print(s)
else:
	d = {}
	for i in a:
		if i not in d:
			d[i] = 1
		else:
			d[i] = d[i] + 1

	def find(i):
		global flag
		if i in d and d[i] > 0:
			d[i] = d[i] - 1
			return i
		for j in range(int(i), -1, -1):
			flag = 1
			j = str(j)
			if j in d and d[j] > 0:
				d[j] = d[j] - 1
				return j

	def fun(d):
		l = []
		for i in d:
			if d[i] > 0:
				l = l + [int(i)] * d[i]
		l.sort()
		l = l[::-1]
		temp = [str(i) for i in l]
		s = ''.join(temp)
		return s

	def fun2(x):
		global new
		for i in range(x - 1, -1, -1):
			temp = new[i]
			for j in range(int(temp) - 1, -1, -1):
				j = str(j)
				if j in d and d[j] > 0:
					new = new[:i] + str(j)
					d[j] = d[j] - 1
					d[temp] = d[temp] + 1
					return new
			d[temp] = d[temp] + 1
	flag = 0
	new = ''
	for i in range(len(b)):
		if flag == 0:
			temp = find(b[i])
			if temp == None:
				new = fun2(i)
				new = new + fun(d)
				break
			else:
				new = new + temp
		else:
			new = new + fun(d)
			break
	print(new)


a = list(reversed(sorted(map(int, input()))))
b = list(map(int, input()))
if len(b) > len(a):
	print(*a, sep='')
else:
	ans = []
	for i in range(len(b)):
		if b[i] in a:
			ans.append(b[i])
			a.remove(b[i])
		else:
			while b[i] <= min(a):
				a.append(ans.pop())
				i -= 1
			a.sort(reverse=True)
			for j in a:
				if j < b[i]:
					ans.append(j)
					a.remove(j)
					break
			print(*ans, sep='', end='')
			print(*a, sep='')
			break
	else:
		print(*ans, sep='')


import sys
a = list(input())
tmp = a
b = int(input())
ans = []
a.sort()
for i in range(len(tmp)):
	for j in range(len(tmp) - 1, -1, -1):
		s = ans[:i] + a[j:j + 1] + a[:j] + a[j + 1:]
		if int(''.join(s)) <= b and ''.join(ans) <= ''.join(s):
			ans = s
			a.remove(a[j])
			break
print(''.join(ans))


import bisect

def solve(l, d, s2, r):
	ans = ''
	lol = 0
	i = 0
	lo = 0
	while i < len(s2):
		if lo == 1:
			a = s2[i]
			ind = bisect.bisect_left(l, a)
			for x in range(ind, -1, -1):
				if l[x] < l[ind]:
					ind = x
					break
			ans += str(l[ind])
			d[l.pop(ind)] -= 1
			lol = 1
			break
		a = s2[i]
		ind = bisect.bisect_left(l, a)
		if ind == len(l):
			ind -= 1
			ans += str(l[ind])
			d[l[ind]] -= 1
			lol = 1
			break
		elif l[ind] > a:
			if ind == 0:
				while ind == 0:
					l.append(int(ans[-1]))
					d[int(ans[-1])] += 1
					l.sort()
					ans = ans[:len(ans) - 1]
					lo = 1
					i -= 1
					a = s2[i]
					ind = bisect.bisect_left(l, a)
				continue
			lol = 1
			ans += str(l[ind - 1])
			d[l[ind - 1]] -= 1
			l.pop(ind - 1)
			break
		else:
			ans += str(l[ind])
			d[l[ind]] -= 1
			l.pop(ind)
		i += 1
	ll = []
	if lol:
		for i in d:
			if d[i] != 0:
				ll.append(i)
		ll.sort(reverse=True)
		co = 0
		for i in ll:
			for j in range(d[i]):
				if i == 0:
					co += 1
					if co > r:
						break
				ans += str(i)
	print(ans)
from math import gcd
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
s1 = list(map(int, input().strip()))
s2 = list(map(int, input().strip()))
z = s1.count(0)
d = dd(int)
n = len(s1)
m = len(s2)
l = sorted(s1)
for i in s1:
	d[i] += 1
if len(s1) < len(s2):
	for i in range(len(s1) - 1, -1, -1):
		print(l[i], end='')
elif len(s1) > len(s2):
	r = m - (n - z)
	l = l[z - r:]
	solve(l, d, s2, r)
else:
	solve(l, d, s2, 100)


a = input()
b = input()
if len(a) < len(b):
	a = sorted(a)[::-1]
	print(''.join(a))
	exit(0)

def check(res, j, a):
	added = False
	tmp = ''
	for i in a:
		if i == j and (not added):
			added = True
		else:
			tmp += i
	tmp = res + j + tmp[::-1]
	return tmp <= b
res = ''
n = len(a)
a = sorted(list(a))[::-1]
for i in range(n):
	for j in a:
		if check(res, j, a):
			res += j
			a.remove(j)
			break
print(res)


def c(a, b, l, ans, pro):
	if l != 0:
		n = a[:]
		mx = None
		pro1 = pro
		prosh = set()
		for i in range(l):
			pro = pro1
			if a[i] == prosh:
				continue
			elif a[i] <= b[0] and pro:
				n.pop(i)
				prosh = a[i]
				if pro == True:
					if a[i] < b[0]:
						pro = False
				m = c(n, b[1:], l - 1, ans + str(a[i]), pro)
				n = a[:]
				if m != None:
					if mx == None:
						mx = int(m)
					elif mx < int(m):
						mx = int(m)
			elif not pro:
				a.sort(reverse=True)
				a = list(map(str, a))
				return ans + ''.join(a)
			else:
				break
		return mx
	else:
		return ans
a = input()
b = input()
l = len(a)
if len(a) != len(b):
	a = list(a)
	a.sort()
	print(''.join(a[::-1]))
else:
	a = list(map(int, a))
	b = list(map(int, b))
	a.sort()
	n = a[:]
	mx = 0
	prosh = -1
	for i in range(l):
		if a[i] == prosh:
			continue
		elif a[i] != 0 and a[i] <= b[0]:
			n.pop(i)
			prosh = a[i]
			pro = False
			if a[i] == b[0]:
				pro = True
			m = c(n, b[1:], l - 1, str(a[i]), pro)
			n = a[:]
			if m != None:
				if mx < int(m):
					mx = int(m)
		elif a[i] > b[0]:
			break
	print(mx)


a = list(input())
b = input()
a.sort(reverse=True)
ans = []
equal_so_far = True
if len(a) < len(b):
	print(''.join(a))
	exit()
for i in range(len(b)):
	for digit in a:
		c = a[:]
		c.remove(digit)
		if not equal_so_far or digit < b[i] or (digit == b[i] and list(sorted(c)) <= list(b[i + 1:])):
			if b[i] != digit:
				equal_so_far = False
			ans.append(digit)
			a.remove(digit)
			break
print(''.join(ans))


def solve(a, b):
	a = str(a)
	b = str(b)
	if len(a) < len(b):
		return greedy(a)
	else:
		return recur(a, b)

def recur(a, b, flag=True):
	if b:
		this = b[0]
		if this in a and flag:
			r = recur(a.replace(this, '', 1), b[1:])
			if r and r[-1] == '*':
				return recur(a, b, False)
			else:
				return this + r
		else:
			tmp = '*'
			for x in a:
				if tmp < x < this:
					tmp = x
			if tmp == '*':
				return '*'
			else:
				a = a.replace(tmp, '', 1)
				return tmp + greedy(a)
	else:
		return ''

def greedy(s):
	return ''.join(sorted(s, reverse=True))
a = int(input())
b = int(input())
print(solve(a, b))


def permute(a, b):
	d = {}
	if len(a) == len(b) and len(a) == 1:
		if int(a) <= int(b):
			return a
		else:
			return '-1'
	for alpha in a:
		try:
			d[alpha] += 1
		except KeyError:
			d[alpha] = 1
	if len(a) < len(b):
		strs = ''
		for i in range(0, 10)[::-1]:
			try:
				strs += d[str(i)] * str(i)
			except:
				pass
		return strs
	elif len(a) == len(b):
		try:
			i = d[b[0]]
			s = permute(a.replace(b[0], '', 1), b[1:])
			if s != '-1':
				return b[0] + s
			else:
				i = int(b[0]) - 1
				while i >= 0:
					try:
						d[str(i)] -= 1
						strs = str(i)
						for i in range(0, 10)[::-1]:
							try:
								strs += d[str(i)] * str(i)
							except:
								pass
						return strs
					except:
						i -= 1
				return '-1'
		except KeyError:
			i = int(b[0]) - 1
			while i >= 0:
				try:
					d[str(i)] -= 1
					strs = str(i)
					for i in range(0, 10)[::-1]:
						try:
							strs += d[str(i)] * str(i)
						except:
							pass
					return strs
				except:
					i -= 1
			return '-1'
a = input()
b = input()
d = {}
print(permute(a, b))


(a, b) = (sorted(input()), input())
(r, p) = (range(len(a)), lambda x: int(''.join(x)))
for i in r:
	for j in r[i:]:
		(a[i], a[j], c) = (a[j], a[i], p(a))
		if not c <= p(a) <= p(b):
			(a[i], a[j]) = (a[j], a[i])
print(p(a))


def swap_n_sort(X, i, j):
	X = X[0:i] + X[j] + X[i + 1:j] + X[i] + X[j + 1:]
	X = X[:i + 1] + ''.join(reversed(sorted(X[i + 1:])))
	return X
X = ''.join(reversed(sorted(input())))
Y = input()
if len(X) < len(Y):
	print(X)
else:
	eq = True
	i = 0
	while i < len(X):
		if int(''.join(X)) < int(''.join(Y)):
			break
		x = int(X[i])
		y = int(Y[i])
		if x < y:
			break
		if x == y and eq == True:
			i += 1
		if x > y or (x == y and eq == False):
			nx = -1
			nj = -1
			for j in range(i + 1, len(X)):
				xx = int(X[j])
				if (xx <= y and eq == True or (xx < y and eq == False)) and xx > nx:
					nj = j
					nx = int(X[j])
			if nx > -1:
				X = swap_n_sort(X, i, nj)
				i += 1
			else:
				i -= 1
				eq = False
	print(X)


def permuteDigits():
	low = list(input().strip())
	high = list(input().strip())
	if len(low) < len(high):
		low.sort()
		low.reverse()
		print(''.join(low))
	else:
		li = []
		i = 0
		string = ''
		while True:
			if high[i] in low:
				for j in range(len(low)):
					if low[j] == high[i] and j not in li:
						li.append(j)
						string += low[j]
						break
				else:
					break
				i += 1
				if i == len(low):
					print(string)
					return
				continue
			break
		li.sort()
		for item in range(len(li) - 1, -1, -1):
			del low[li[item]]
		low.sort()
		if min(low) < high[i]:
			for p in range(len(low) - 1, -1, -1):
				if int(low[p]) < int(high[i]):
					string += low[p]
					del low[p]
					break
			for p in range(len(low) - 1, -1, -1):
				string += low[p]
		else:
			while True:
				i -= 1
				if min(low) < high[i]:
					break
				low.append(high[i])
				string = string[:-1]
			low.sort()
			for p in range(len(low) - 1, -1, -1):
				if low[p] < high[i]:
					temp = string[-1]
					string = string[:-1]
					string += low[p]
					del low[p]
					low.append(temp)
					break
			low.sort()
			for p in range(len(low) - 1, -1, -1):
				string += low[p]
		print(string)
permuteDigits()


from collections import Counter

def can_make(c, b, l):
	d = Counter(c)
	for i in range(l):
		if d[b[i]] == 0:
			return False
		d[b[i]] -= 1
	res = int(b[l])
	for x in range(res - 1, -1, -1):
		if d[str(x)] > 0:
			return True
	return False

def main():
	a = input()
	b = input()
	if len(a) < len(b):
		a = list(a)
		a.sort(reverse=True)
		print(''.join(a))
		return
	c = Counter(a)
	if c == Counter(b):
		print(b)
		return
	for i in range(len(b) - 1, -1, -1):
		if can_make(c, b, i):
			res = i
			break
	out = []
	for i in range(res):
		out.append(b[i])
		c[b[i]] -= 1
	x = int(b[res])
	for y in range(x - 1, -1, -1):
		sy = str(y)
		if c[sy] > 0:
			out.append(sy)
			c[sy] -= 1
			break
	for y in range(9, -1, -1):
		sy = str(y)
		out += [sy] * c[sy]
	print(''.join(out))
main()


a = input()
b = input()
v = sorted(a)
v = v[::-1]
x = ''
for i in range(len(v)):
	x = x + v[i]
v = x
if len(a) < len(b):
	print(v)
elif b == a:
	print(a)
else:
	fin = ''
	flag = False
	for j in range(len(a)):
		for k in range(len(a)):
			num = fin + v[k] + ''.join(sorted(v[:k] + v[k + 1:]))
			if num <= b:
				fin += v[k]
				if int(v[k]) < int(b[j]):
					flag = True
					v = v[:k] + v[k + 1:]
					fin += v
				v = v[:k] + v[k + 1:]
				break
		if flag:
			break
	print(fin)


a = sorted(list(input()))
b = input()
if len(a) < len(b):
	print(''.join(a[::-1]))
	exit()
result = [None] * len(b)
pos = 0
while pos < len(b):
	is_exit = False
	for i in range(len(a)):
		cur = a[~i]
		if cur <= b[pos]:
			result[pos] = cur
			a.remove(cur)
			if cur < b[pos]:
				is_exit = True
			else:
				pos += 1
			break
	else:
		while not is_exit:
			pos -= 1
			smaller_than = result[pos]
			a += [smaller_than]
			a.sort()
			result[pos] = None
			for i in range(len(a)):
				cur = a[~i]
				if cur < smaller_than:
					result[pos] = cur
					a.remove(cur)
					is_exit = True
					break
	if is_exit:
		break
print(''.join(result[:pos + 1] + a[::-1]))


def main(a, b, w=False):
	if not b:
		return None if a else ''
	if len(a) < len(b):
		return ''.join(sorted(a)[::-1])
	if ''.join(sorted(a)) > b:
		return
	if b[0] in a:
		i = a.index(b[0])
		(a[i], a[0]) = (a[0], a[i])
		m = main(a[1:], b[1:], True)
		if m is not None:
			return a[0] + m
	for i in reversed(range(1 - w, int(b[0]))):
		if str(i) in a:
			ind = a.index(str(i))
			(a[ind], a[0]) = (a[0], a[ind])
			m = ''.join(sorted(a[1:])[::-1])
			if m is not None:
				return a[0] + m
	return
a = input()
b = input()
print(main(list(a), b))


def main():
	a = sorted(input(), reverse=True)
	b = int(input())
	k = ''
	while len(a) > 0:
		for i in range(len(a)):
			num = k + a[i] + ''.join(sorted(a[:i] + a[i + 1:]))
			if int(num) <= b:
				k += a[i]
				a = a[:i] + a[i + 1:]
				break
	print(k)
main()


import bisect

def main():
	a = list(input())
	b = list(input())
	a.sort()
	ans = ''
	if len(a) < len(b):
		ans = ''.join(reversed(a))
	else:
		for i in range(len(b)):
			idx = bisect.bisect_left(a, b[i])
			if idx < len(a) and a[idx] == b[i]:
				del a[idx]
				if a > b[i + 1:]:
					ans += a[idx - 1]
					a[idx - 1] = b[i]
					ans += ''.join(reversed(a))
					break
				ans += b[i]
			else:
				ans += a.pop(idx - 1)
				ans += ''.join(reversed(a))
				break
	print(ans)
main()


def main():
	a = list(input())
	b = list(input())
	n = len(a)
	if n < len(b):
		a.sort()
		a.reverse()
		print(''.join(a))
		return
	b_ = [int(_) for _ in b]
	a.sort()
	a.reverse()
	a_ = [int(_) for _ in a]
	c = [0 for _ in range(n)]
	r = []
	index = 0
	flag = 0
	while index < n:
		now = b_[index]
		if now < 0:
			b_[index] = 0
			index -= 1
			b_[index] -= 1
			r = []
			c = [0 for _ in range(n)]
			index = 0
			continue
		ma = -1
		for i in range(n):
			if c[i]:
				continue
			if a_[i] <= now:
				c[i] = 1
				ma = a_[i]
				break
		if ma is -1:
			b_[index] = 9
			index -= 1
			b_[index] -= 1
			r = []
			c = [0 for _ in range(n)]
			index = 0
			continue
		r.append(ma)
		if ma < int(b[index]):
			flag = 1
			break
		index += 1
	if flag is 1:
		for each in r:
			print(each, end='')
			a_.remove(each)
		for each in a_:
			print(each, end='')
		print()
		return
	for each in r:
		print(each, end='')
	print()
main()


def tryf(s, ii, u, dont, preff):
	usd = u.copy()
	for i in range(len(s), len(b)):
		for k in range(len(a)):
			if not usd[k]:
				if i == ii and a[k] == dont:
					continue
				if preff and a[k] < b[i]:
					preff = False
					s += a[k]
					usd[k] = True
					break
				elif preff and a[k] == b[i]:
					s += a[k]
					usd[k] = True
					break
				elif not preff:
					s += a[k]
					usd[k] = True
					break
	if len(s) == len(a):
		return s
	return '0'
a = input()
b = input()
a = list(a)
a.sort(reverse=True)
used = [False for i in range(len(a))]
pref = True
prefs = []
if len(a) < len(b):
	print(''.join(a))
else:
	ans = ''
	for i in range(len(a)):
		prefs.append(pref)
		for k in range(len(a)):
			if not used[k]:
				if pref and a[k] < b[i]:
					pref = False
					ans += a[k]
					used[k] = True
					break
				elif pref and a[k] == b[i]:
					ans += a[k]
					used[k] = True
					break
				elif not pref:
					ans += a[k]
					used[k] = True
					break
		else:
			break
	if len(ans) == len(a):
		print(ans)
	else:
		for j in range(len(ans) - 1, -1, -1):
			for k in range(len(a)):
				if a[k] == ans[j] and used[k]:
					used[k] = False
					break
			s = tryf(ans[:j], j, used, ans[j], prefs[j])
			if s != '0':
				print(s)
				break


def checkIfLower(num):
	if int(num) <= int(req):
		return True

def swapped(a, b):
	arr = list(inp)
	temp = arr[b]
	arr[b] = arr[a]
	arr[a] = temp
	return ''.join(arr)

def findMax():
	global inp
	for i in range(len(inp)):
		for x in range(i, len(inp)):
			if inp[i] < inp[x]:
				temp = swapped(i, x)
				if checkIfLower(temp):
					inp = temp
	print(inp)
inp = input()
req = input()
if int(inp) == int(req):
	print(inp)
else:
	temp = list(inp)
	temp.sort()
	inp = ''.join(temp)
	findMax()


s = input()
a = [int(s[i]) for i in range(len(s))]
s = input()
b = [int(s[i]) for i in range(len(s))]
if len(a) < len(b):
	a.sort()
	a = a[::-1]
	print(*a, sep='')
else:
	kek = [0] * 10
	kekos = [0] * 10
	for i in range(len(a)):
		kek[a[i]] += 1
		kekos[a[i]] += 1
	ans = 0
	g = [-1] * len(b)
	for i in range(len(b)):
		j = b[i]
		for t in range(j):
			if kek[t] > 0:
				g[i] = t
		if kek[j] > 0:
			ans += 1
			kek[j] -= 1
		else:
			break
	if ans == len(b):
		print(*b, sep='')
	else:
		k = ans
		while g[k] == -1:
			k -= 1
		for i in range(k):
			print(b[i], end='')
			kekos[b[i]] -= 1
		print(g[k], end='')
		kekos[g[k]] -= 1
		for i in range(9, -1, -1):
			for j in range(kekos[i]):
				print(i, end='')


def y(a, b):
	if len(a) < len(b):
		a.sort(reverse=1)
		return a
	c = b[0]
	if c in a:
		if len(b) == 1:
			return [c]
		a.remove(c)
		d = y(a[:], b[1:])
		if d:
			return [c] + d
		a += c
	e = list(filter(lambda x: x < c, a))
	if e:
		e = max(e)
		a.remove(e)
		a.sort(reverse=1)
		return [e] + a
	return False
a = list(input())
b = list(input())
ans = y(a, b)
print(''.join(ans))


a = input()
b = input()
digits = list(a)
builder = ''
if len(b) < len(a):
	b = b.rjust(len(a), '0')
for digit in b:
	if len(b) > len(a):
		break
	if digit in digits:
		digits.remove(digit)
		if int(builder + digit + ''.join(sorted(digits, key=int))) <= int(b):
			builder += digit
			continue
		else:
			digits.append(digit)
	added = max([d for d in digits if d < digit])
	builder += added
	digits.remove(added)
	break
builder += ''.join(sorted(digits, reverse=True, key=int))
print(builder)


fre = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
a = input()
b = input()
c = False

def DFS(aa, bb):
	if int(aa) == len(a):
		print(bb)
		exit()
	global c
	for i in range(9, -1, -1):
		if fre[i] > 0 and i <= int(b[int(aa)]) or (fre[i] > 0 and c):
			fre[i] -= 1
			if i < int(b[int(aa)]):
				c = True
			DFS(aa + 1, bb * 10 + i)
			fre[i] += 1
			c = False
if len(b) > len(a):
	x = sorted(a)
	print(*x[::-1], sep='')
else:
	for i in a:
		fre[int(i)] += 1
	DFS(0, 0)


a = input()
b = input()
la = [int(x) for x in a]
res = []
la.sort()
la = la[::-1]
lb = [int(x) for x in b]
cnt = [0] * 20

def check():
	tres = 0
	for x in range(len(res)):
		tres *= 10
		tres += int(res[x])
	return tres <= int(b)
if len(a) < len(b):
	for i in range(len(la)):
		print(la[i], end='')
	print()
else:
	for i in range(len(la)):
		cnt[la[i]] += 1
	flag = 0
	for i in range(len(lb)):
		if flag == 0 and cnt[lb[i]]:
			res.append(lb[i])
			cnt[lb[i]] -= 1
		else:
			flag = i - 1
			for j in range(lb[i] - 1, -1, -1):
				if cnt[j]:
					res.append(j)
					cnt[j] -= 1
					break
			for j in range(9, -1, -1):
				while cnt[j]:
					res.append(j)
					cnt[j] -= 1
			break
	while not check():
		temp = []
		cnt = [0] * 20
		for x in range(flag):
			temp.append(res[x])
			cnt[res[x]] -= 1
		for i in la:
			cnt[i] += 1
		res = temp
		for v in range(lb[flag] - 1, -1, -1):
			if cnt[v]:
				res.append(v)
				cnt[v] -= 1
				break
		for v in range(9, -1, -1):
			while cnt[v]:
				res.append(v)
				cnt[v] -= 1
		flag -= 1
	for i in range(len(res)):
		print(res[i], end='')
	print()


def check(e, value, pre):
	global maxi, count
	e[str(value)] -= 1
	pre += str(value)
	arr = []
	for i in e:
		for j in range(e[i]):
			arr.append(i)
	arr.sort(reverse=True)
	st = ''
	for i in arr:
		st += str(i)
	alpha = int(pre + st)
	if alpha <= int(b):
		maxi = max(maxi, int(pre + st))
a = input()
b = input()
maxi = 0
d = {}
for i in a:
	if i not in d:
		d[i] = 1
	else:
		d[i] += 1
maxi = 0
num = ''
count = 0
if len(a) < len(b):
	check(d.copy(), max(d), '')
else:
	for i in b:
		if i in d and d[i] > 0:
			for j in range(int(i) - 1, -1, -1):
				if str(j) in d and d[str(j)] > 0:
					check(d.copy(), j, num)
					break
			check(d.copy(), i, num)
			num += i
			d[i] -= 1
		else:
			j = 0
			for j in range(int(i) - 1, -1, -1):
				if str(j) in d and d[str(j)] > 0:
					check(d.copy(), j, num)
					break
			break
print(maxi)


import sys
(a, b) = (input(), input())
if len(a) < len(b):
	print(*sorted(a, reverse=True), sep='')
	exit()
cnt = [0] * 10
for x in a:
	cnt[int(x)] += 1

def rec(res, digit, rem):
	if digit == len(b):
		return res
	if rem[int(b[digit])]:
		r = rem[:]
		r[int(b[digit])] -= 1
		x = rec(res + b[digit], digit + 1, r)
		if x:
			return x
	for d in range(int(b[digit]) - 1, -1, -1):
		if rem[d]:
			res += str(d)
			rem[d] -= 1
			suf = []
			for i in range(10):
				suf += [str(i)] * rem[i]
			return res + ''.join(sorted(suf, reverse=True))
	return ''
ans = rec('', 0, cnt[:])
print(ans)


a = input()
b = input()
o = 0
t = []
i = 0
h = 0
c = 0
w = 0
j = 0
l = [int(d) for d in a]
k = [int(i) for i in b]
l.sort()
l.reverse()
if len(l) < len(k):
	print(''.join(map(str, l)))
if len(l) == len(k):
	for i in range(0, len(k)):
		o = k[i]
		if o in l:
			t.append(o)
			l.remove(o)
			l.sort()
			l.reverse()
			h = len(t)
		else:
			while o not in l and o >= 0:
				o = o - 1
			if o in l:
				t.append(o)
				l.remove(o)
				l.sort()
				l.reverse()
				break
			else:
				while c != 1:
					for j in range(0, len(l)):
						if t[h - 1] > l[j]:
							c = c + 1
							w = l[j]
							break
					l.append(t[h - 1])
					l.sort()
					l.reverse()
					del t[h - 1]
					h = len(t)
				t.append(w)
				l.remove(w)
				l.sort()
				l.reverse()
				break
	print(''.join(map(str, t + l)))


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time, copy, functools
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
eps = 1.0 / 10 ** 15
mod = 10 ** 9 + 7

def LI():
	return [int(x) for x in sys.stdin.readline().split()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def main():
	a = [c for c in S()]
	b = [c for c in S()]
	r = []
	if len(a) < len(b):
		r = sorted(a, reverse=True)
	else:
		a.sort()
		la = len(a)
		for i in range(la):
			k = 0
			for j in range(len(a) - 1, -1, -1):
				if a[j] > b[i]:
					continue
				if a[j] == b[i]:
					t = a[:j] + a[j + 1:]
					if t <= b[i + 1:]:
						k = j
						break
					continue
				k = j
				break
			r.append(a[k])
			a = a[:k] + a[k + 1:]
			if r[-1] < b[i]:
				r += sorted(a, reverse=True)
				break
	return ''.join(r)
print(main())


def find(l, x):
	a = sorted([y for y in l if y <= x])
	if len(a) > 0:
		return a[-1]
	return l[0]

def find_less(l, x):
	a = sorted([y for y in l if y < x])
	if len(a) > 0:
		return a[-1]
	return None

def main():
	a = input()
	b = input()
	if len(a) < len(b):
		print(''.join(sorted(a, reverse=True)))
		return
	a = list(a)
	res = []
	invalid = False
	for x in b:
		y = find(a, x)
		if y == x:
			res.append(x)
			a.remove(y)
		elif y < x:
			res.append(y)
			a.remove(y)
			res += sorted(a, reverse=True)
			break
		else:
			invalid = True
			break
	if not invalid:
		print(''.join(res))
		return
	idx = len(res)
	while idx >= 0:
		x = b[idx]
		y = find_less(a, x)
		if y is not None:
			res.append(y)
			a.remove(y)
			res += sorted(a, reverse=True)
			break
		else:
			a.append(res.pop())
			idx -= 1
	assert len(res) == len(b)
	print(''.join(res))
main()


a = list(input())
b = input()
out = []
mx = '/'
a.sort()
a.reverse()
x = len(a)
if x == len(b):
	for i in range(x):
		q = 0
		for j in range(len(a)):
			if a[j] == b[i]:
				out.append(a[j])
				a.pop(a.index(a[j]))
				q = 1
				break
			elif a[j] < b[i]:
				out.append(a[j])
				a.pop(a.index(a[j]))
				print(''.join(out), end='')
				print(''.join(a))
				exit(0)
		if q == 0:
			break
	if q == 1:
		print(''.join(out))
	else:
		y = len(out)
		for i in range(y - 1, -1, -1):
			for j in range(len(a)):
				if a[j] < b[i] and a[j] > mx:
					mx = a[j]
			if mx != '/':
				a.append(out[len(out) - 1])
				out.pop()
				out.append(mx)
				a.pop(a.index(mx))
				a.sort()
				a.reverse()
				print(''.join(out), end='')
				print(''.join(a))
				exit(0)
			else:
				a.append(out[len(out) - 1])
				out.pop()
				a.sort()
				a.reverse()
		a.pop(a.index(mx))
		print(mx, end='')
		print(''.join(a))
else:
	print(''.join(a))


def f(b, l, i, ls, below=False):
	if i == len(b):
		return True
	ne = int(b[i])
	if below:
		ne = 9
	found = False
	for j in range(ne, -1, -1):
		if ls[j] > 0:
			l.append(j)
			ls[j] -= 1
			val = f(b, l, i + 1, ls, True if below or j < ne else False)
			ls[j] += 1
			if val:
				found = True
				break
			else:
				l.pop()
	return found
a = input()
b = input()
if len(b) > len(a):
	print(''.join(sorted(a, reverse=True)))
l = []
ls = [0] * 11
for x in a:
	ls[int(x)] += 1
f(b, l, 0, ls)
print(''.join(map(str, l)))


def check(ans, num, a, b, u):
	prob = ans
	a = []
	for i in range(len(num)):
		a.append(num[i])
	prob += num[u]
	a.pop(u)
	a.sort()
	for i in range(len(a)):
		prob += a[i]
	if int(prob) <= int(b):
		return True
	return False
a = input()
b = input()
num = []
ans = ''
if len(a) == len(b):
	for i in range(len(a)):
		num.append(a[i])
	num.sort()
	num.reverse()
	step = 0
	while num:
		for i in range(len(num)):
			if check(ans, num, a, b, i):
				ans += num[i]
				num.pop(i)
				break
	if num:
		ans += num[-1]
	print(ans)
else:
	num = []
	for i in range(len(a)):
		num.append(a[i])
	num.sort()
	num.reverse()
	ans = ''
	for i in range(len(num)):
		ans += num[i]
	print(ans)


import bisect

def get_int(l, xa, j):
	return int(''.join(l + [xa[j]] + sorted(xa[:j] + xa[j + 1:])))

def f(a, b):
	if len(a) < len(b):
		return int(''.join(reversed(sorted(a))))
	xa = list(sorted(a))
	xb = list(b)
	ib = int(b)
	m = int(''.join(xa))
	l = []
	for i in range(len(xb)):
		(mj, r) = (0, 0)
		for j in range(len(xa)):
			if get_int(l, xa, j) <= ib:
				r = get_int(l, xa, j)
				mj = j
		l.append(xa[mj])
		xa = xa[:mj] + xa[mj + 1:]
	return int(''.join(l))

def test_f():
	assert f('123', '222') == 213
	assert f('129', '1000') == 921
	assert f('125', '222') == 215
	assert f('4940', '5000') == 4940
	assert f('321', '500') == 321
a = input()
b = input()
print(f(a, b))


a = input()
b = input()
list_a = list(a)
list_a.sort()
max_a = int(''.join(list_a))
for i in range(len(a)):
	for j in range(i + 1, len(a)):
		(list_a[i], list_a[j]) = (list_a[j], list_a[i])
		temp_a = int(''.join(list_a))
		if int(b) < temp_a or temp_a <= max_a:
			(list_a[i], list_a[j]) = (list_a[j], list_a[i])
		else:
			max_a = temp_a
print(max_a)


def make_number(b, chars):
	if len(chars) == 0:
		return ''
	target = chars[0]
	for i in chars:
		if int(b[0]) <= int(i):
			break
		target = i
	chars.remove(target)
	return target + ''.join(chars[::-1])

def find_number(b, chars):
	backup_chars = list(chars)
	if len(b) == 1:
		return chars[0]
	elif b[0] in chars:
		chars.remove(b[0])
		num = b[0] + find_number(b[1:], chars)
		if min(num, b) == b and b != num:
			return make_number(b, backup_chars)
		else:
			return num
	else:
		return make_number(b, backup_chars)
(a, b) = (str(input()), str(input()))
chars = [i for i in a]
chars.sort()
if len(a) < len(b):
	print(''.join(chars[::-1]))
else:
	print(find_number(b, chars))