#include <bits/stdc++.h>
using namespace std;
int poww(int i) {
  int p = 1;
  for (int j = 1; j <= i; j++) p *= 10;
  return p;
}
int main() {
  double t, n;
  cin >> t;
  while (t--) {
    cin >> n;
    int number_of_digits = 0, def_digit = 10, right_most;
    int temp = n;
    while (temp) {
      int rem = (int)temp % 10;
      number_of_digits++;
      temp = temp / 10;
      if (temp == 0) {
        right_most = rem;
      }
    }
    int ans = (number_of_digits - 1) * 9 + right_most - 1;
    int gen_num = 0;
    for (int i = 0; i <= number_of_digits - 1; i++) {
      int num = right_most * poww(i);
      gen_num += num;
    }
    if (n >= gen_num) ans++;
    cout << ans << "\n";
  }
  return 0;
}
