#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#define int long long
#define rep(i, n) for(i = 0; i < n; i++)
#define rrep(i, n) for(i = n - 1; i >= 0; i--)
using namespace std;

int mod = 1000000007;
int m;
string c;
int ad[10];

void print(vector<int> perm) {
	int i;
	rep(i, c.length()) {
		int num = perm[c[i] - '0'];
		cout << num;
	}
	cout << endl;
}

signed main() {
	int i;
	
	cin >> m >> c;
	
	int p10 = 1;
	rrep(i, c.length()) {
		ad[c[i] - '0'] += p10;
		ad[c[i] - '0'] %= mod;
		p10 *= 10;
		p10 %= mod;
	}
	
	vector<int> perm;
	rep(i, 10) perm.push_back(i);
	do {
		if (c.length() >= 2 && perm[c[0] - '0'] == 0) continue;
		int res = 0;
		rep(i, 10) {
			res += ad[i] * perm[i];
			res %= mod;
		}
		if (res == m) { print(perm); return 0; }
	} while (next_permutation(perm.begin(), perm.end()));
	
	cout << -1 << endl;
	return 0;
}
