#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int D, l, ans, k, d, t, i, p;
  string m, n;
  cin >> t;
  while (t--) {
    cin >> n;
    p = 0;
    ans = 0;
    l = 0;
    d = n.size();
    ans = 9 * (d - 1);
    D = 0;
    for (i = 0; i < d; i++) {
      m[i] = n[0];
    }
    p = 0;
    for (i = 0; i < d; i++) {
      if ((long long int)m[i] - (long long int)n[i] < 0) {
        p = 1;
        break;
      } else if ((long long int)m[i] - (long long int)n[i] > 0) {
        p = -1;
        break;
      } else {
      }
    }
    if (p == 1 || p == 0) {
      D = (long long int)n[0];
      D = D - 48;
      ans = ans + (D);
    } else {
      D = (long long int)n[0];
      D = D - 48;
      ans = ans + D - 1;
    }
    cout << ans << endl;
  }
  return 0;
}
