#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int n, m, i, j, k, l;
  string s;
  long long int t;
  cin >> t;
  while (t--) {
    cin >> s;
    long long int x = s.size();
    long long int a[] = {1,      11,      111,      1111,      11111,
                         111111, 1111111, 11111111, 111111111, 1111111111};
    stringstream geek(s);
    long long int xx = 0;
    geek >> xx;
    long long int res = xx / a[x - 1];
    long long int res1 = (x - 1) * 9;
    cout << res + res1 << endl;
  }
  return 0;
}
