#include <bits/stdc++.h>
using namespace std;
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long q;
  cin >> q;
  while (q--) {
    long long n;
    cin >> n;
    long long m = n, t = 0;
    long long c = 0;
    while (m) {
      t = m % 10;
      c++;
      m /= 10;
    }
    long long ans = (c - 1) * 9;
    ans += (t - 1);
    long long mm = 0;
    while (c--) {
      mm = mm * 10 + t;
    }
    if (n >= mm) ans++;
    cout << ans << endl;
  }
  return 0;
}
