#include <iostream>
using namespace std;
int num[10];

void solve() {
    num[0] = num[1] = num[2] = 0;
    string s;
    cin >> s;
    int n = s.length(), sum = 0, res = 0;

    for (int i = 0; i < n; i++) {
        sum += s[i] - '0';
        num[(s[i] - '0') % 3]++;
    }

    sum %= 3;
    if (sum == 0) {
        if (num[0] == n) {
            cout << n - 1 << endl;
        } else {
            cout << num[0] << endl;
        }
    } else {
        for (int i = n - 1; i >= 0; i--) {
            if ((s[i] - '0') % 3 == sum) {
                if (i == 0) {
                    i++;
                    while (s[i] == '0') i++;
                    if (num[0] == n - 1) {
                        cout << num[0] - i + 1 << endl;
                    } else {
                        cout << num[0] - i + 2 << endl;
                    }
                } else {
                    if (num[0] == n - 1) {
                        cout << n - 2 << endl;
                    } else {
                        cout << num[0] + 1 << endl;
                    }
                }
                return;
            }
        }
        cout << 0 << endl;
    }
}

int main() {
    int t;
    cin >> t;
    while (t--) {
        solve();
    }
    return 0;
}