#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cassert>

using namespace std;

int main()
{
	ifstream in("award.in");

	int tc;
	in >>tc;
	while (tc--)
	{
		int age, s, r = 0, p = 1;
		string award;
		in >>age >>award;
		s = age % 10 + 2;		

		for (int i = award.length()-1;i >= 0;i--, p *= s)
			if (award[i] == 'A')
				r += 10*p;
			else
				r += (award[i] - '0') * p;
		cout <<r <<endl;
	}

	return 0;
}
