#include <bits/stdc++.h>
const long long int mod = 1000000007;
const long long inf = 1e18;
long long int power(long long int x, long long int y) {
  long long int res = 1;
  x = x % mod;
  while (y > 0) {
    if (y & 1) res = (res * x) % mod;
    y = y >> 1;
    x = (x * x) % mod;
  }
  return res;
}
long long int ncr(long long int n, long long int r) {
  long long int C[r + 1];
  memset(C, 0, sizeof(C));
  C[0] = 1;
  for (long long int i = 1; i <= n; i++) {
    long long int t = i;
    if (r < t) t = r;
    for (long long int j = t; j > 0; j--) C[j] = C[j] + C[j - 1];
  }
  return C[r];
}
long long int gcd(long long int a, long long int b) {
  if (a == 0) return b;
  return gcd(b % a, a);
}
long long int lcm(long long int a, long long int b) {
  return (a / gcd(a, b) * b);
}
clock_t time_p = clock();
double rtime() {
  time_p = clock() - time_p;
  return (double)(time_p) / CLOCKS_PER_SEC;
}
using namespace std;
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long int t;
  cin >> t;
  while (t--) {
    long long int n;
    cin >> n;
    long long int cnt = 0;
    for (long long int i = 1; i <= 9; i++) {
      long long int x = 0, y = 0;
      x = i;
      while (x <= n) {
        x = x * 10 + i;
        y++;
      }
      cnt += y;
    }
    cout << cnt << endl;
  }
  return 0;
}
