#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int maxn = 3e5 + 7;
int a[maxn];
int main() {
  int k = 1;
  a[0] = 0;
  for (int i = 1; i <= 9; i++) {
    int s = 0;
    for (int j = 0; j < 9; j++) {
      a[k++] = s = s * 10 + i;
    }
  }
  sort(a, a + k);
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int u = lower_bound(a, a + k, n) - a;
    printf("%d\n", (a[u] == n) ? u : (u - 1));
  }
  return 0;
}
