#include <bits/stdc++.h>
using namespace std;
inline long long gi() {
  long long w = 0, q = 0;
  char c = getchar();
  while ((c < '0' || c > '9') && (c != '-')) c = getchar();
  if (c == '-') q = 1, c = getchar();
  while (c >= '0' && c <= '9') w = w * 10 + c - '0', c = getchar();
  return q ? -w : w;
}
int T, tot;
long long n, t[3000], s[3000];
int main() {
  scanf("%d", &T), t[1] = 1, s[1] = 1;
  for (int i = 2; i <= 39; ++i) t[i] = t[i - 1] * 3ll, s[i] = s[i - 1] + t[i];
  while (T--) {
    n = gi();
    int a = 39;
    long long sum = 0;
    while (n > 0) {
      while (n <= s[a]) a--;
      sum += t[a + 1], n -= t[a + 1];
    }
    printf("%I64d\n", sum);
  }
  return 0;
}
