#include <bits/stdc++.h>
using namespace std;
int fun (int n)
{
    int ans=0;
    while(n)
    {
        n=n/10;
        ans++;
    }
    return ans-1;
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    cin>>t;
    while(t--)
    {
        int n, res=0;
        cin>>n;
        int nod = 0;
        nod = fun(n);
        res = 9*nod;
      
        nod++;
        string s = to_string(n);
        int f_no = s[0]-'0';
        
        res+=f_no-1;
        string z="";
        while(nod--)
        {
            z+=s[0];
        }
        int num = stoi(z);
        if(num<=n)
        res++;
        cout<<res<<endl;
    }
    return 0;
}