#include <bits/stdc++.h>
using namespace std;
const int MOD = int(1e9) + 7;
const long long int MOD64 = (long long int)(1e18) + 7;
const int INF = 0x7fffffff;
const long long int INF64 = 0x7fffffffffffffff;
const int N = 1e5 + 10;
long long int p[50];
long long int sum[50];
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  p[0] = 1;
  sum[0] = 1;
  for (int i = int(1); i < int(40); i++) {
    p[i] = p[i - 1] * 3;
    sum[i] = sum[i - 1] + p[i];
  }
  int q;
  cin >> q;
  while (q--) {
    long long int n;
    cin >> n;
    long long int ans = 0;
    int i = 39;
    while (i >= 0) {
      if (n > sum[i]) {
        ans += p[i + 1];
        n -= p[i + 1];
        if (n <= 0) break;
      } else if (n == sum[i]) {
        ans += sum[i];
        break;
      }
      i--;
    }
    cout << ans << endl;
  }
  return 0;
}
