#include<bits/stdc++.h>
#define rep(i,n) for(int i=0 ; i<n ; i++)
#define ll long long 
#define pb push_back
#define mp make_pair
#define all(x) x.begin(),x.end()
using namespace std;
const ll MX=1e6+2;
const ll MOD=1e9+7;

int main(){
    int t;
    cin>>t;
    while(t--){
        ll n;
        cin>>n;
        ll s=floor(log10(n))+1;
        vector<ll> A;
        rep(i,9){
            ll a=i+1,b=i+1;
            rep(j,s-1){
                b*=10;
                b+=a;
            }
            A.pb(b);
        }
        ll ans=0;
        for(auto el:A){
            if(el<=n)ans++;
        }
        ll an=9*(s-1)+ans;
        cout<<an<<endl;
    }
}