#include <bits/stdc++.h>
using namespace std;
long long t, d, ans;
string n, s;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin >> t;
  while (t--) {
    cin >> n;
    if (n.size() == 1) {
      cout << n << "\n";
      continue;
    }
    d = n.size();
    s.resize(d);
    for (long long i = 0; i < d; i++) s[i] = n[0];
    ans = (d - 1) * 9 + (s[0] - '1');
    if (s <= n) ans++;
    cout << ans << "\n";
  }
  return 0;
}
