#include <bits/stdc++.h>
using namespace std;
long long mod = 1e9 + 7;
long long gcdll(long long a, long long b) {
  if (!b) return a;
  return gcdll(b, a % b);
}
int gcd(int a, int b) {
  if (!b) return a;
  return gcd(b, a % b);
}
void seive(int n) {
  vector<bool> is_prime(n + 1, true);
  is_prime[0] = is_prime[1] = false;
  for (int i = 2; i * i <= n; i++) {
    if (is_prime[i]) {
      for (int j = i * i; j <= n; j += i) {
        is_prime[j] = false;
      }
    }
  }
}
vector<int> constructZFunc(string s) {
  int n = s.size();
  vector<int> z(n);
  int l, r;
  l = r = 0;
  z[0] = 0;
  for (int i = 1; i <= n - 1; i++) {
    z[i] = 0;
    if (i <= r) {
      z[i] = min(r - i + 1, z[i - l]);
    }
    while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i];
    if (i + z[i] - 1 > r) {
      r = i + z[i] - 1;
      l = i;
    }
  }
  return z;
}
int solve(long long n) {
  int d = 0;
  long long t = n;
  long long z = 0;
  while (n >= 10) {
    d++;
    n /= 10;
  }
  long long fac = 1;
  for (int i = 0; i <= d; i++) {
    z += fac * n;
    fac *= 10ll;
  }
  int ans = 9 * d;
  if (t < z)
    ans += n - 1;
  else
    ans += n;
  return ans;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    long long n;
    cin >> n;
    cout << solve(n) << endl;
  }
  return 0;
}
