#include <bits/stdc++.h>
using namespace std;
const int Mod = 1e9 + 7;
void solve() {
  string s;
  cin >> s;
  long long int ans = 9 * (s.length() - 1) + (s[0] - '0');
  for (long long int i = (0); i < (s.length() - 1); i++) {
    if (s[i] == s[i + 1])
      continue;
    else {
      if (s[i] > s[i + 1]) ans--;
      break;
    }
  }
  cout << ans << '\n';
}
int main() {
  try {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t = 0;
    cin >> t;
    while (t--) solve();
  } catch (...) {
  }
  return 0;
}
