#include <bits/stdc++.h>
using namespace std;
int n;
long long sum = 0;
string test;
int main() {
  cin >> n;
  while (n--) {
    sum = 0;
    cin >> test;
    int flag = 1;
    sum += 9 * (test.size() - 1);
    int t = int(test[0] - '0');
    sum += t;
    for (int i = 1; i < test.size(); i++) {
      if (int(test[i] - '0') == t) continue;
      if (int(test[i] - '0') < t) sum--;
      break;
    }
    cout << sum << endl;
  }
  return 0;
}
