#include <bits/stdc++.h>
using namespace std;
int main() {
  int t, i, n;
  cin >> t;
  long long int a, b, j, k, m;
  for (i = 0; i < t; i++) {
    n = 0;
    m = 0;
    cin >> a;
    j = a;
    while (a != 0) {
      n++;
      k = a;
      a = a / 10;
    }
    for (int o = 0; o < n; o++) {
      m = m + pow(10, o);
    }
    m = k * m;
    if (j >= m)
      b = 9 * (n - 1) + j / pow(10, n - 1);
    else
      b = 9 * (n - 1) + j / pow(10, n - 1) - 1;
    cout << b << endl;
  }
  return 0;
}
