#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef unsigned long long ull;

vector<ull> nums;
int high_digits[] = {5, 7, 8, 9};

void dfs(int last_idx, vector<int>& digits) {
    vector<int> sorted = digits;
    std::sort(sorted.begin(), sorted.end());
    ull val = 0;
    if (sorted.empty()) val = 1;
    else {
        if (sorted.size() > 19) return;
        for (int d : sorted) {
            if (val > 2000000000000000000ULL) { 
                val = 2000000000000000001ULL; 
                break; 
            }
            val = val * 10 + d;
        }
    }
    if (val > 1000000000000000000ULL) return;
    nums.push_back(val);

    for (int i = last_idx; i < 4; i++) {
        digits.push_back(high_digits[i]);
        dfs(i, digits);
        digits.pop_back();
    }
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    vector<vector<int>> tails = {
        {},
        {2},
        {3},
        {4},
        {6},
        {2, 6}
    };
    for (auto& t : tails) {
        dfs(0, t);
    }
    sort(nums.begin(), nums.end());
    nums.erase(unique(nums.begin(), nums.end()), nums.end());
    int t;
    if (cin >> t) {
        while (t--) {
            ull n;
            cin >> n;
            int count = upper_bound(nums.begin(), nums.end(), n) - nums.begin();
            if (n >= 10) count++; 
            cout << count << "\n";
        }
    }
    return 0;
}