#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
void solve() {
  long long n;
  cin >> n;
  long long ans = 0;
  for (long long num = 1; num <= 9; num++) {
    long long val = 0;
    for (long long len = 1; len <= 9; len++) {
      val = val * 10 + num;
      if (val <= n) ans++;
    }
  }
  cout << ans << endl;
  return;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  ;
  long long t;
  cin >> t;
  while (t--) solve();
  return 0;
}
