#include <bits/stdc++.h>
using namespace std;
long long int gcd(long long int a, long long int b) {
  return b == 0 ? a : gcd(b, a % b);
}
long long int power(long long int x, long long int n) {
  long long int result = 1;
  while (n > 0) {
    if (n % 2 == 1) result = (result * x) % 1000000007;
    x = (x * x) % 1000000007;
    n = n / 2;
  }
  return result % 1000000007;
}
long long int bS(long long int arr[], long long int l, long long int r,
                 long long int x) {
  if (r >= l) {
    long long int mid = l + (r - l) / 2;
    if (arr[mid] == x) return mid;
    if (arr[mid] > x) return bS(arr, l, mid - 1, x);
    return bS(arr, mid + 1, r, x);
  }
  return -1;
}
int 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 a[9] = {0}, x, y, r = 0, count = 0;
    x = n;
    while (x != 0) {
      x = x / 10;
      r++;
    }
    if (r == 1)
      cout << n << '\n';
    else {
      y = n;
      long long int i = 0;
      while (y != 0) {
        a[i] = y % 10;
        y = y / 10;
        i++;
      }
      count = (r - 1) * 9;
      r--;
      long long int d = 0, s = n / pow(10, r);
      for (long long int k = 0; k < i; k++) d = d + (s * pow(10, k));
      if (n < d)
        count += s - 1;
      else if (d > n)
        count += s + 1;
      else
        count += s;
      cout << count << '\n';
    }
  }
  return 0;
}
