#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <climits>
#include <queue>
#include <set>
#include <map>
#include <valarray>
#include <bitset>
#include <stack>
using namespace std;

#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
typedef long long ll;
typedef pair<int,int> pii;
const int INF = 1<<29;
const double PI = acos(-1);
const double EPS = 1e-8;

ll int2int(ll src, int base) {
  string res;
  while(src != 0) {
    char c = src%base;
    if (c < 10) c += '0';
    else c += 'a'-10;
    res = string(1,c) + res;
    src /= base;
  }
  FOR(it, res) if (!isdigit(*it)) return -1;
  return atoi(res.c_str());
}

int main() {
  ll A,B,C;
  while(cin>>A>>B>>C,A!=-1) {
    bool f = 0;
    for (int i=2; i<=16; ++i) {
      if (B == int2int(A,i)) {
        f = 1;
        break;
      }
    }
    if (!f) {
      puts("-1");
      continue;
    }
    for (int i=A+1; i<=C; ++i) {
      ll next = -1;
      for (int j=2; j<=16; ++j) {
        ll k = int2int(i,j);
        if (k >= B) {
          if (next == -1 || next > k) {
            next = k;
          }
        }
      }
      B = next;
    }
    cout << B << endl;
  }
}