#include<bits/stdc++.h>
#include<vector>
#include<algorithm>
#include<string> 
using namespace std;
#define fastio ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
//#define printclock cerr<<"Time : "<<1000*(ld)clock()/(ld)CLOCKS_PER_SEC<<"ms\n"
#define ll long long int
#define ld long double
#define ull unsigned long long
#define li long int
#define str string
#define fr(i,n) for(ll i = 0; i<n; i++)

int main() {

	fastio;
    int t;
    cin>>t;
    while(t--){
        ll n;
        cin>>n;
        if(n<10){
          cout<<n<<endl;
        }
        else{
        ll p=n;
        int count=0,a=0;
        while(p!=0){
          int rem=p%10;
          count++;
          if(p<10){
            a=rem;
           }
            p=p/10;
        }
        ll temp = 0;
        for(int i=0;i<count;i++){
           temp+=a*pow(10,i);
        }
        //cout<<temp<<endl;
        if(n>=temp){
          cout<<(9*(count-1) + a)<<endl;
        }
        else
          cout<<(9*(count-1) +a -1)<<endl;
        }

    }
	return 0;
}