#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<math.h>
#include<complex>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<functional>
#include<assert.h>
#include<numeric>
using namespace std;
#define REP(i,m,n) for(int i=(int)(m) ; i < (int) (n) ; ++i )
#define rep(i,n) REP(i,0,n)
using ll = long long;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;
const ll mod=1e9+7 ;

int main(){
    int m;
    cin>>m;
    string s;
    cin>>s;
    vector<ll> x(10);
    int n = s.size();
    int top = s[0]-'0';
    rep(i,n){
        rep(j,10)(x[j]*=10)%=mod;
        x[s[i]-'0']++;
    }
    vector<ll> p(10);
    iota(p.begin(),p.end(),0);
    do{
        if(p[top]==0&&s.size()>=2)continue;
        ll res = 0;
        rep(j,10)res += p[j]*x[j]%mod;
        if(res%mod==m){
            rep(i,n){
                int x = s[i]-'0';
                cout<<p[x];
            }
            cout<<endl;
            return 0;
        }
    }while(next_permutation(p.begin(), p.end()));
    cout<<-1<<endl;
    return 0;
}
