#include<bits/stdc++.h>
using namespace std;
int main() {
int base,t;
string numStr;
cin>>t;
while (t>0){
cin >> base >> numStr;
if (base == 10) {
cout << numStr;
return 0;
}
long long result = 0;
for (int i = 0; i < numStr.size(); ++i) {
char c = numStr[i];
int digit;
if (c >= '0' && c <= '9') {
digit = c - '0';
}
else if (c >= 'A' && c <= 'Z') {
digit = c - 'A' + 10;
}
else if (c >= 'a' && c <= 'z') {
digit = c - 'a' + 10;
}
result = result * base + digit;
}
cout << result <<endl;
t--;
}
return 0;
}