#include <bits/stdc++.h>
using namespace std;
using namespace std::chrono;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  long long int t;
  cin >> t;
  while (t--) {
    long long int n;
    cin >> n;
    long long int count = 0;
    for (long long int digit = 1; digit <= 10; digit++) {
      for (long long int x = 1; x <= 9; x++) {
        string s = "";
        for (long long int y = 1; y <= digit; y++) {
          s += (char)(x + 48);
        }
        long long int nu = stoll(s);
        if (nu <= n) {
          count++;
        }
      }
    }
    cout << count << "\n";
  }
  return 0;
}
