#include #include void solve() { using namespace std; string s; cin >> s; int n = s.size() - 1; constexpr int inv[] = {0, 1, 5, 0, 7, 2, 0, 4, 8}; bool all_zero = true; int ans = 0, comb = 1, e = 0; for (int i = 0; i <= n; i++) { int c = s[i] - '0'; all_zero &= (c == 0); if (e == 0) { ans += c * comb; } if (e == 1) { ans += c * comb * 3; } ans %= 9; if (i == n) { break; } int k = n - i; while (k % 3 == 0) { k /= 3; e++; } comb *= k; k = i + 1; while (k % 3 == 0) { k /= 3; e--; } comb *= inv[k % 9]; comb %= 9; } if (!all_zero && ans == 0) { ans = 9; } cout << ans << "\n"; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int t; std::cin >> t; while (t--) { solve(); } }