#include <bits/stdc++.h>
using namespace std;
int main() {
  int i, j, k, t, sum;
  cin >> t;
  while (t--) {
    string s, z;
    cin >> s;
    int sm = 0;
    stringstream sss(s);
    sss >> sm;
    int x = s.size();
    sum = (x - 1) * 9;
    int nm1 = s[0] - '0';
    for (i = 0; i < x; i++) {
      z += '1';
    }
    int zm = 0;
    stringstream zzz(z);
    zzz >> zm;
    int temp = nm1 * zm;
    if (temp <= sm) {
      temp = nm1;
    } else
      temp = nm1 - 1;
    sum = sum + temp;
    cout << sum << endl;
  }
}
