#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int Ull;
typedef pair<int ,int> PII;
template <typename T>
inline T  read()
{
    char c=getchar();
    T x=0,f=1;
    while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
    while(isdigit(c))x=(x<<3)+(x<<1)+(c^48),c=getchar();
    return x*f;
}
template <typename T>
inline void write(T x) 
{
    if(x < 0) x = (~x) + 1, putchar('-');
    if(x / 10) write(x / 10);
    putchar(x % 10 | 48);
}
const int INF = 0x3f3f3f3f;
const ll N = 1e5+10;
int jug(int n){
    for(int i = 1; i <= 10; i++){
        int x = pow(10,i);
        int a = n / x;
        if(!a)
            return i;
    }
}
int main(){
    //ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0); 
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        int num = jug(n);
        int ans = 9*(num-1);
        int x = n / pow(10,num-1);
        int y = x;
        for(int i = 1; i < num; i++){
            x = x*10+y;
        }
        if(x <= n) ans += y;
        else ans += (y-1);
        cout<<ans<<"\n";
    }

}