#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    string s;
    cin >> s;
    long long n = s.size();
    long long ans = 9 * (n - 1);
    long long x = s[0] - '0';
    ans = ans + (x - 1);
    long long v[100] = {0};
    for (long long i = 0; i < n; i++) {
      v[s[i] - '0']++;
    }
    long long w = 0;
    for (long long i = 0; i < 10; i++) {
      if (v[i] == n) {
        w = 1;
        break;
      }
    }
    if (s.size() > 1)
      for (long long i = 1; i < n; i++) {
        if (s[i] == s[0])
          continue;
        else if (s[i] > s[0]) {
          w = 1;
          break;
        } else {
          break;
        }
      }
    if (w) ans++;
    cout << ans << '\n';
  }
}
