#include
#include
//任意z进制数v转10进制的函数
int n2ten(char v[],int z)
{
int res=0;
int f=1;
int i=0;
if(v[0]=='-'){
f=-1;
i=1;
}
for (;i { int a; if(v[i]>='0'&&v[i]<='9') { a=v[i]-'0'; } else if(v[i]>='A'&&v[i]<='Z') { a=10+v[i]-'A'; } else { a=36+v[i]-'a'; } res=res*z+a; } return res*f; } int main() { int n; scanf("%d",&n); while(n--) { char a[100],b[100]; int az,bz; scanf("%s%d%s%d",a,&az,b,&bz); printf("%d\n",n2ten(a,az)+n2ten(b,bz)); } return 0; }