#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int T, N;
  cin >> T;
  for (int t = 0; t < T; ++t) {
    cin >> N;
    int aux = N;
    int power = 0, ans = 0;
    while (aux) {
      power++;
      aux /= 10;
    }
    ans = (power - 1) * 9;
    int tens = 1;
    power--;
    while (power--) tens *= 10;
    ans += N / tens - 1;
    int d = (N / tens) % 10;
    int b = 0;
    while (tens) {
      b *= 10;
      b += d;
      tens /= 10;
    }
    cout << ans + (N >= b) << endl;
  }
  return 0;
}
