#include <bits/stdc++.h>
using namespace std ;
int N ( char a ) {
if ( a == 'A' ) return 10 ;
if ( a == 'B' ) return 11 ;
if ( a == 'C' ) return 12 ;
if ( a == 'D' ) return 13 ;
if ( a == 'E' ) return 14 ;
if ( a == 'F' ) return 15 ;
return int ( a - '0' ) ;
}
long long f ( int x, string s ) {
long long S = 0 ;
for ( int i = 0 ; i < s.size () ; i++ ) {
S+=N(s[i])*pow(x,s.size()-i-1);
} return S ;
}
int main () {
int n, x ; string s ; cin >> n ;
for ( int i = 1 ; i <= n ; i++ ) {
cin >> x >> s ; cout << f ( x, s ) << endl ;
}
return 0 ;
}