#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    int n, temp, c = 0, ans = 0;
    cin >> n;
    temp = n;
    while (temp > 9) {
      c++;
      temp /= 10;
    }
    ans += c * 9;
    ans += temp - 1;
    int temp1 = 0;
    for (int i = 1; i <= c + 1; i++) temp1 = temp1 * 10 + temp;
    if (n >= temp1) ans++;
    cout << ans << "\n";
  }
}
