#include <bits/stdc++.h>
using namespace std;
const long long INF = 2e18;
int q;
long long n;
long long solve(long long n, long long cur) {
  long long minAns;
  if (n > (cur * 3 - 1) / 2)
    return -1;
  else if (n <= 0)
    return 0;
  long long ans = solve(n - cur, cur / 3);
  if (ans != -1) minAns = ans + cur;
  ans = solve(n, cur / 3);
  if (ans != -1) minAns = min(minAns, ans);
  return minAns;
}
int main() {
  cin >> q;
  for (int i = 0; i < q; i++) {
    cin >> n;
    long long cur = 1;
    while (cur < n) {
      cur *= 3;
    }
    cout << solve(n, cur) << endl;
  }
}
