#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
#define MOD 1000000007
#define ar array
#define fast_io ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); 

int32_t main() {
    fast_io;
 
	int t; cin >> t;
	while (t--) {
		int n; cin >> n;
		int num_dig = 0; vector<int> digs;
		while (n) {
			digs.push_back(n % 10);
			num_dig++;
			n /= 10;
		}
		reverse(digs.begin(), digs.end());
		int first_dig = digs[0];
		int can_do = true;
		for (int i = 1; i < digs.size(); i++) {
			if (digs[i] < first_dig) {
				can_do = false;
			}
			else if (digs[i] > first_dig) {
				break;
			}
		}
		if (!can_do) first_dig--;
		cout << 9*(num_dig - 1) + first_dig << endl;
	}
    
    return 0;
}
