#include using namespace std; typedef long long ll; typedef vector vi; typedef vector vl; typedef pair pii; typedef pair pll; typedef int _loop_int; #define REP(i,n) for(_loop_int i=0;i<(_loop_int)(n);++i) #define FOR(i,a,b) for(_loop_int i=(_loop_int)(a);i<(_loop_int)(b);++i) #define FORR(i,a,b) for(_loop_int i=(_loop_int)(b)-1;i>=(_loop_int)(a);--i) #define DEBUG(x) cout<<#x<<": "< P; char buf[125252]; int inv[] = {0,1,5,0,7,2,0,4,8}; void solve(){ scanf("%s",buf); int n = strlen(buf); if(count(buf,buf+n,'0')==n){ puts("0"); return; } if(n==1){ puts(buf); return; } int a = 1; int tri = 0; int ans = 0; REP(i,n){ if(tri==0){ ans += a*(buf[i]-'0')%9; }else if(tri==1){ ans += a*3*(buf[i]-'0')%9; } a *= (n-1-i); while(a!=0 && a%3==0){ a/=3; tri++; } int b = i+1; while(b!=0 && b%3==0){ b/=3; tri--; } a *= inv[b%9]; } ans%=9; if(ans==0)ans=9; printf("%d\n",ans); } int main(){ int t; scanf("%d",&t); while(t--)solve(); return 0; }