#include <bits/stdc++.h>
using namespace std;
int main() {
  int t, i, j;
  cin >> t;
  for (i = 0; i < t; i++) {
    string s;
    cin >> s;
    int sum;
    string b = "";
    if (stoi(s) >= 1 && stoi(s) <= 9) {
      sum = stoi(s);
    } else {
      for (j = 0; j < s.length(); j++) {
        b.push_back(s[0]);
      }
      sum = (s.length() - 1) * 9;
      if (stoi(s) < stoi(b)) {
        sum = sum + (s[0] - '0') - 1;
      } else {
        sum = sum + (s[0] - '0');
      }
    }
    cout << sum << endl;
  }
}
