#include <climits>
#include <cmath>
#include <cstddef>
#include <iostream>
#include <vector>

using namespace std;

int isOrdinary(int n) {
    int ordinary = 1;
 
    int num = n % 10;
    n = n / 10;
    while(n) {
        int current = n % 10;
        n = n / 10;
        if (current != num) {
            return 0;
        }
    }
    return 1;
}

int getNoIncurrentBand(int n, int digits) {
    int no = 0;
    for(int i = 0; i < digits; i++) {
        no = no + n * pow(10, i);
    }
    return no;
}

int main () {
    int t;
    cin >> t;

    int n;

    while (t--) {
        cin >> n;

        int original = n;
        int ans = 0;

        if (original >= 1 && original <= 9) {
            cout << original << "\n";
        } else {
            int digits = 0;
            while (n) {
                n = n/10;
                digits++;
            }

            ans = (digits - 1) * 9;

            n = original;

            int starting = n / pow(10, digits - 1);

            ans = ans + starting - 1;

            if (n >= getNoIncurrentBand(starting, digits)) {
                ans++;
            }

            cout << ans << "\n";

        }

    }
}
