#include <bits/stdc++.h>
using namespace std;
inline void solve() {
  string n;
  cin >> n;
  if (n.size() == 1) {
    cout << n << "\n";
  } else {
    int res = 0;
    res += (n.size() - 1) * 9;
    string num;
    for (int i = 0; i < n.size(); ++i) {
      num += n[0];
    }
    if (stoi(n) >= stoi(num)) {
      res += n[0] - '0';
    } else {
      res += n[0] - '0' - 1;
    }
    cout << res << "\n";
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t-- > 0) {
    solve();
  }
}
