#include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <cstdint>
using namespace std;
typedef long long ll;
#define MP make_pair
#define PB push_back
#define inf 1000000007
#define mod 1000000007
#define rep(i,n) for(int i = 0; i < (int)(n); ++i)
#define int long long

int p[10];

signed main(){
    int m;
    string c;
    cin >> m >> c;
    int s = 1;
    if(c.size()==1&&m==0){
        cout << 0 << endl;
        return 0;
    }
    reverse(c.begin(),c.end());
    int n = c.size();
    int k = 0;
    rep(i,n){
        p[c[i]-'0'] +=s;
        p[c[i]-'0'] %= mod;
        s *=10;
        s %= mod;
        k = c[i]-'0';
    }
    vector<int> v(10);
    rep(i,10){
        v[i] = i;
    }
    string t;
    bool ok = 0;
    do{
        int sm = 0;
        rep(i,10){
            sm += p[i] * v[i];
            sm%= mod;
        }
        if(sm==m&&v[k]!=0){
            rep(i,n){
                t.push_back(v[c[i]-'0']+'0');
            } 
            ok = true;
            break;
        }  
    }while(next_permutation(v.begin(),v.end()));
    if(ok){
        reverse(t.begin(),t.end());
        cout << t << endl;
    }else{
        cout << -1 << endl;
    }
    return 0;
}
