#include <bits/stdc++.h>
using namespace std;
long long solve(vector<long long> &v, long long pos, long long val) {
  if (pos == 0) {
    if (val > 1) {
      return -1;
    }
    return val;
  }
  if (v[pos] >= val) {
    long long w = solve(v, pos - 1, val);
    if (w == -1) return v[pos];
    return min(w, v[pos]);
  } else {
    long long w = solve(v, pos - 1, val - v[pos]);
    if (w == -1) return -1;
    return v[pos] + w;
  }
}
int32_t main() {
  vector<long long> v;
  v.push_back(1);
  for (long long i = 1; i < 60; i++) {
    v.push_back((long long)v.back() * 3LL);
    if (v.back() > 1e18) break;
  }
  vector<long long> pref(v.size());
  pref[0] = 1;
  for (long long i = 1; i < (long long)v.size(); i++) {
    pref[i] = pref[i - 1] + v[i];
  }
  long long t;
  cin >> t;
  while (t--) {
    long long n;
    cin >> n;
    long long pt = lower_bound(v.begin(), v.end(), n) - v.begin();
    if (v[pt] == n) {
      cout << n << endl;
      continue;
    }
    if (pref[pt - 1] < n) {
      cout << v[pt] << endl;
      continue;
    }
    long long ans = v[pt];
    long long val = n - v[pt - 1];
    long long res = solve(v, pt - 1, val);
    if (res == -1) {
      cout << ans << endl;
    } else {
      cout << min(v[pt - 1] + res, ans) << endl;
    }
  }
  return 0;
}
