#include <bits/stdc++.h>
int main() {
  long int t;
  scanf("%ld", &t);
  while (t--) {
    long int r = 0;
    char str[10];
    scanf("%s", str);
    long int k = str[0] - '0';
    long int len = strlen(str);
    long int h = 0, m = 0, q = 1;
    for (long int i = len - 1; i >= 0; i--) {
      int b = str[i] - '0';
      m += k * q;
      h += b * q;
      q *= 10;
    }
    long int ans;
    if (h >= m)
      ans = 9 * (len - 1) + k;
    else
      ans = 9 * (len - 1) + k - 1;
    printf("%ld\n", ans);
  }
  return 0;
}
