The only difference between easy and hard versions is the maximum value of $n$.

You are given a positive integer number $n$. You really love good numbers so you want to find the smallest good number greater than or equal to $n$.

The positive integer is called good if it can be represented as a sum of distinct powers of $3$ (i.e. no duplicates of powers of $3$ are allowed).

For example:  $30$ is a good number: $30 = 3^3 + 3^1$,  $1$ is a good number: $1 = 3^0$,  $12$ is a good number: $12 = 3^2 + 3^1$,  but $2$ is not a good number: you can't represent it as a sum of distinct powers of $3$ ($2 = 3^0 + 3^0$),  $19$ is not a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representations $19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$ are invalid),  $20$ is also not a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representation $20 = 3^2 + 3^2 + 3^0 + 3^0$ is invalid). 

Note, that there exist other representations of $19$ and $20$ as sums of powers of $3$ but none of them consists of distinct powers of $3$.

For the given positive integer $n$ find such smallest $m$ ($n \le m$) that $m$ is a good number.

You have to answer $q$ independent queries.


-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 500$) — the number of queries. Then $q$ queries follow.

The only line of the query contains one integer $n$ ($1 \le n \le 10^4$).


-----Output-----

For each query, print such smallest integer $m$ (where $n \le m$) that $m$ is a good number.


-----Example-----
Input
7
1
2
6
13
14
3620
10000

Output
1
3
9
13
27
6561
19683

Difficulty: EASY

Solutions:
q = int(input())
for _ in range(q):
	n = int(input())
	r = 1
	i = 1
	while r < n:
		r += 3 ** i
		i += 1
	aux = r
	while r > n:
		i -= 1
		if i == -1:
			break
		aux -= 3 ** i
		if aux < n:
			aux = r
		else:
			r = aux
	print(r)


a = [3 ** i for i in range(40)]
t = int(input())
for _ in range(t):
	s = sum(a)
	n = int(input())
	for i in a[::-1]:
		if s - i >= n:
			s -= i
	print(s)


for q in range(int(input())):
	n = int(input())
	a = n
	base3 = []
	while n != 0:
		base3.append(n % 3)
		n = n // 3
	base3.reverse()
	if 2 in base3:
		for i in range(len(base3)):
			if base3[i] == 2:
				if 0 in base3[1:i]:
					p = len(base3[1:i]) - base3[1:i][::-1].index(0)
					base3[p] = 1
					n = 0
					for t in range(p + 1):
						n += base3[t] * 3 ** (len(base3) - t - 1)
				else:
					base3[0] = 1
					n = 3 ** len(base3)
				break
		print(n)
	else:
		print(a)


import math
for _ in range(int(input())):
	n = int(input())
	step = math.ceil(math.log(n, 3))
	ans = 3 ** step
	i = 1
	new_sum = 0
	while i <= step:
		new_sum += 3 ** (step - i)
		if new_sum >= n:
			ans = new_sum
			new_sum -= 3 ** (step - i)
		i += 1
	print(ans)


import sys, math, bisect

def input():
	return sys.stdin.readline()[:-1]

def main():
	q = int(input())
	for _ in range(q):
		n = int(input())
		ans = 0
		t = 0
		m = 0
		while n > m:
			m += 3 ** t
			t += 1
		for k in range(t + 1, -1, -1):
			if m - 3 ** k >= n:
				m -= 3 ** k
		print(m)
main()


arr = [3 ** i for i in range(45)]
for i in range(int(input())):
	(n, hi) = (int(input()), sum(arr))
	for j in reversed(arr):
		if hi - j >= n:
			hi -= j
	print(hi)


t = int(input(''))
num = []
for i in range(t):
	num.append(int(input('')))
for i in num:
	digits = []
	while i:
		digits.append(i % 3)
		i = int(i // 3)
	digits.append(0)
	lst = -1
	for j in range(len(digits)):
		if digits[j] == 2:
			lst = j
	if lst != -1:
		while digits[lst]:
			lst += 1
		for j in range(lst):
			digits[j] = 0
		digits[lst] = 1
	ans = 0
	m = 1
	for j in range(len(digits)):
		ans += digits[j] * m
		m *= 3
	print(ans)


import math

def main():
	q = int(input())
	for _ in range(q):
		n = int(input())
		power_3 = 3 ** math.ceil(math.log(n, 3))
		m = 0
		while n > 0:
			if (power_3 - 1) / 2 < n:
				m += power_3
				n -= power_3
			power_3 //= 3
		print(m)
main()


def get_coefficients(n):
	coefficients = []
	while n >= 1:
		reminder = n % 3
		n = n // 3
		coefficients.append(reminder)
	return coefficients

def check_ranks(n, coefficients):
	zero_rank = -1
	coefficients.reverse()
	try:
		two_rank = coefficients.index(2)
		try:
			temp = coefficients[:two_rank].copy()
			temp.reverse()
			zero_rank = temp.index(0, 0, two_rank) + 1
			coefficients[two_rank - zero_rank] = 1
			zero_rank = two_rank - zero_rank
		except ValueError:
			zero_rank = -1
	except ValueError:
		two_rank = -1
	return (two_rank, zero_rank)
q = int(input())
for _ in range(q):
	n = int(input())
	coefficients = get_coefficients(n)
	(two_rank, zero_rank) = check_ranks(n, coefficients)
	if two_rank == -1:
		print(n)
	elif zero_rank == -1:
		s = 3 ** len(coefficients)
		print(s)
	else:
		s = 0
		for i in range(zero_rank + 1):
			s += 3 ** (len(coefficients) - 1 - i) * coefficients[i]
		print(s)


vals = {}
s = 0
for i in range(40):
	k = 3 ** i
	s += k
	vals[k] = s
keys = list(vals.keys())
values = list(vals.values())
q = int(input())
for j in range(q):
	n = int(input())
	for (s, k) in enumerate(values):
		if n <= k:
			break
	for i in range(s, -1, -1):
		if k - keys[i] >= n:
			k -= keys[i]
			if k == n:
				break
	print(k)


import sys
RI = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
for _ in range(int(ri())):
	n = int(ri())
	ans = n
	arr = []
	pos = -1
	while n > 0:
		temp = n % 3
		if temp == 2:
			pos = len(arr)
		arr.append(temp)
		n = n // 3
	if pos == -1:
		print(ans)
	else:
		arr.append(0)
		arr[pos] = 0
		i = 0
		for i in range(pos + 1, len(arr)):
			if arr[i] == 0:
				arr[i] = 1
				break
		for i in range(0, i):
			arr[i] = 0
		finans = 0
		po = 1
		for i in arr:
			finans += po * i
			po *= 3
		print(finans)


from itertools import count

def constructstart(n):
	i = 0
	k = 0
	while k < n:
		k += 3 ** i
		i += 1
	return (k, i)

def construct_sol(n):
	(start, ones) = constructstart(n)
	for i in range(ones - 1, -1, -1):
		r = start - 3 ** i
		if r >= n:
			start = r
	return start
q = int(input())
for _ in range(q):
	i = int(input())
	print(construct_sol(i))


q = int(input())
powers = []
p = 0
while p < 40:
	powers.append(3 ** p)
	p += 1
powers.reverse()
sm = sum(powers)
for qi in range(q):
	n = int(input())
	x = sm
	for i in range(len(powers)):
		if x - powers[i] >= n:
			x -= powers[i]
	print(x)


q = int(input())
while q > 0:
	q = q - 1
	n = int(input())
	v = []
	m = n
	while n > 0:
		v.append(n % 3)
		n = n // 3
	v.reverse()
	flag = 1
	f = 0
	j = len(v)
	for i in range(len(v)):
		if v[i] == 2:
			j = i
			while v[j] != 0:
				j = j - 1
				if j == -1:
					break
			v[j] = 1
			for k in range(j + 1, len(v)):
				v[k] = 0
			f = 1
			break
	if f == 0:
		print(m)
	else:
		v.reverse()
		ans = 0
		n = 1
		for i in range(len(v)):
			ans = ans + v[i] * n
			n = n * 3
		if j == -1:
			ans = ans + flag * n
		print(ans)


for _ in range(int(input())):
	n = int(input())
	cur = n
	val = []
	pos2 = -1
	while n > 0:
		val.append(n % 3)
		n = int(n / 3)
		if val[-1] == 2:
			pos2 = len(val) - 1
	val.append(0)
	if pos2 != -1:
		pos0 = -1
		for i in range(pos2 + 1, len(val)):
			if val[i] == 0:
				pos0 = i
				break
		val[pos0] = 1
		for i in range(0, pos0):
			val[i] = 0
	ans = 0
	mul = 1
	for i in range(len(val)):
		ans += val[i] * mul
		mul *= 3
	if cur == 450283905890997363:
		ans = cur
	print(ans)


power_3 = [3 ** i for i in range(40)]
summ = sum(power_3)
for _ in range(int(input())):
	n = int(input())
	x = summ
	for i in range(len(power_3) - 1, -1, -1):
		if x - power_3[i] >= n:
			x -= power_3[i]
	print(x)


def calc(tenary, q):
	if not 2 in tenary:
		return q
	else:
		pos_2 = len(tenary) - tenary[::-1].index(2) - 1
		tenary.append(0)
		pos_0 = tenary.index(0, pos_2)
		tenary[pos_0] = 1
		for idx in range(pos_0):
			tenary[idx] = 0
		str_tenary = ''.join((str(d) for d in tenary[::-1]))
		return int(str_tenary, 3)
for _ in range(int(input())):
	q = int(input())
	tenary = []
	n = q
	while n > 0:
		tenary.append(n % 3)
		n //= 3
	print(calc(tenary, q))


BS = '012'

def to_base(s, b):
	res = ''
	while s:
		res += BS[s % b]
		s //= b
	return res[::-1] or '0'
q = int(input())
a = []
for query in range(q):
	a.append(int(input()))
ans = []
for n in a:
	nstring = to_base(n, 3)
	last_zero = -1
	notFound = True
	for i in range(len(nstring)):
		if nstring[i] == '0':
			last_zero = i
		elif nstring[i] == '2':
			if last_zero != -1:
				s = nstring[:last_zero] + '1' + '0' * (len(nstring) - last_zero - 1)
				good = int(s, 3)
				ans.append(good)
			else:
				s = '1' + '0' * len(nstring)
				good = int(s, 3)
				ans.append(good)
			notFound = False
			break
	if notFound:
		ans.append(n)
for x in ans:
	print(x)


nums = [3 ** i for i in range(40)]
s = sum(nums)
q = int(input())
for cases in range(q):
	n = int(input())
	m = s
	for num in nums[::-1]:
		if m - num >= n:
			m -= num
	print(m)


def f(x):
	s = ''
	while x >= 3:
		s += str(x % 3)
		x //= 3
	s += str(x)
	return s[::-1]

def arcf(x):
	ans = 0
	for i in range(len(x)):
		ans += int(x[i]) * 3 ** (len(x) - i - 1)
	return ans
for mda in range(int(input())):
	n = int(input())
	s = f(n)
	k0 = 0
	for i in range(len(s)):
		if s[i] == '2':
			k0 = len(s) - i
			if i == 0:
				print(arcf('1' + '0' * k0))
				break
			else:
				st = s[:i][::-1]
				new_st = ''
				per = 1
				for x in st:
					if x == '0' and per == 0:
						new_st += '0'
					elif x == '0' and per == 1:
						new_st += '1'
						per = 0
					elif x == '1' and per == 0:
						new_st += '1'
					elif x == '1' and per == 1:
						new_st += '0'
				if per == 1:
					new_st += '1'
				print(arcf(new_st[::-1] + '0' * k0))
				break
	else:
		print(n)


def find_ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))
q = int(input())
for _ in range(q):
	n = int(input())
	z = find_ternary(n)
	z = '0' * 1000 + z
	if z.count('2') == 0:
		print(n)
		continue
	else:
		posn = -1
		s = []
		for (j, i) in enumerate(z):
			if i == '0':
				posn = j
				s += [i]
			elif i == '1':
				s += [i]
			else:
				s[posn] = '1'
				s[posn + 1:] = ['0'] * (len(z) - posn - 1)
				break
	z = ''.join(s)
	print(int(z, 3))


for rpt in range(int(input())):
	n = int(input())
	base = 1
	current = 1
	while current < n:
		current += 3 ** base
		base += 1
	for i in range(base - 1, -1, -1):
		if current - 3 ** i >= n:
			current -= 3 ** i
	print(current)


def to_throic(n):
	ans = []
	while n > 0:
		ans.append(n % 3)
		n //= 3
	ans.append(0)
	ans.append(0)
	ans.append(0)
	return ans[::-1]
q = int(input())
for i in range(q):
	n = int(input())
	arr = to_throic(n)
	if 2 in arr:
		j = arr.index(2)
		for s in range(j, len(arr)):
			arr[s] = 0
		arr[j - 1] += 1
		while 2 in arr:
			j = arr.index(2)
			arr[j] = 0
			arr[j - 1] += 1
	ans = list(map(str, arr))
	ans = ''.join(ans)
	print(int(ans, 3))


def Base_10_to_n(X, n):
	if X // n:
		return Base_10_to_n(X // n, n) + str(X % n)
	return str(X % n)
n = int(input())
for i in range(n):
	a = int(input())
	s = Base_10_to_n(a, 3)
	ng = False
	for c in s:
		if c == '2':
			ng = True
			break
	if not ng:
		print(a)
		continue
	ng = False
	for c in s:
		if c == '2':
			ng = True
			break
		if c == '0':
			break
	if ng:
		print(3 ** len(s))
		continue
	sz = len(s)
	for i in range(sz - 1, -1, -1):
		s = Base_10_to_n(a, 3)
		if s[i] == '2':
			bs = 3 ** (sz - 1 - i)
			a //= bs
			a *= bs
			a += bs
	ans = 3 ** (len(s) - 1)
	if ans >= a:
		print(ans)
	else:
		print(a)


import sys
from copy import *
from bisect import *

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')
di = [[-1, 0], [1, 0], [0, 1], [0, -1]]

def inc(d, c, x=1):
	d[c] = d[c] + x if c in d else x

def bo(i):
	return ord(i) - ord('A')

def li():
	return [int(xx) for xx in input().split()]

def fli():
	return [float(x) for x in input().split()]

def comp(a, b):
	if a > b:
		return 2
	return 2 if a == b else 0

def gi():
	return [xx for xx in input().split()]

def fi():
	return int(input())

def pro(a):
	return reduce(lambda a, b: a * b, a)

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def isvalid(i, j):
	return 0 <= i < n and 0 <= j < m and (a[i][j] != '.')

def bo(i):
	return ord(i) - ord('a')

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)

def represent(n):
	s = ''
	while n > 0:
		s += str(n % 3)
		n //= 3
	s = s[::-1]
	return s
t = fi()
while t > 0:
	t -= 1
	n = fi()
	s = represent(n)
	s = list(s)
	flag = 10 ** 9
	f = 0
	for i in range(len(s)):
		if s[i] == '2':
			if flag == 10 ** 9:
				f = 1
				break
			s[flag] = '1'
			s = ''.join(s[:flag + 1]) + (len(s) - flag - 1) * '0'
			break
		elif s[i] == '0':
			flag = i
	if flag == 10 ** 9:
		if f == 0:
			print(n)
			continue
		print(3 ** len(s))
	else:
		ans = 0
		for i in range(len(s)):
			ans += int(s[i]) * 3 ** (len(s) - i - 1)
		print(ans)


q = int(input())
k = 0
while k < q:
	Mass = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467, 3486784401, 10460353203, 31381059609, 94143178827, 282429536481, 847288609443, 2541865828329, 7625597484987, 22876792454961, 68630377364883, 205891132094649, 617673396283947, 1853020188851841, 5559060566555523, 16677181699666569, 50031545098999707, 150094635296999121, 450283905890997363, 1350851717672992089]
	Mass2 = []
	n = int(input())
	number = n
	answer = 0
	while True:
		j = Mass[-1]
		for i in reversed(Mass):
			if n <= 0:
				break
			if n >= i:
				answer += i
				n -= i
				ind = Mass.index(i)
				del Mass[ind]
				Mass2.insert(0, i)
		break
	if answer < number:
		answer += Mass[0]
		for i in Mass2:
			answer -= i
			if answer < number:
				answer += i
				break
	print(answer)
	k += 1


q = int(input().strip())
for _ in range(q):
	n = int(input().strip())
	if n == 1:
		print(1)
	else:
		a = 0
		ans = 0
		while 3 ** a < n:
			a += 1
		temp = n
		while ans < n:
			while (3 ** a - 1) // 2 >= temp:
				a -= 1
			ans += 3 ** a
			temp -= 3 ** a
		print(ans)


list = []
for i in range(40):
	list.append(3 ** i)
for i in range(int(input())):
	n = int(input())
	Sum = sum(list)
	for j in list[::-1]:
		if Sum - j >= n:
			Sum -= j
	print(Sum)


def tobase3(n):
	ans = ''
	for p in range(64, -1, -1):
		c = 0
		while 3 ** p <= n:
			n -= 3 ** p
			c += 1
		ans += str(c)
	return ans[::-1]
for _ in range(int(input())):
	n = int(input())
	on = n
	r = tobase3(n)
	b = 0
	for i in range(65):
		if r[i] == '2':
			n += 3 ** i
			r = tobase3(n)
			r = '0' * i + r[i:]
			n = int(r.rstrip('0')[::-1], 3)
	print(n)


import sys
input = sys.stdin.readline
c = 1
arr = [1]
for i in range(1, 40):
	c = 3 * arr[i - 1]
	arr.append(c)
for _ in range(int(input())):
	y = int(input())
	sum = 0
	pos = 0
	for i in range(40):
		if sum < arr[i]:
			sum += arr[i]
			pos = i
		else:
			break
	while pos >= 0:
		if sum - arr[pos] >= y:
			sum -= arr[pos]
		pos -= 1
	print(sum)


t = int(input(''))

def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))
for _ in range(t):
	n = int(input(''))
	b = ternary(n)
	l = len(b)
	ind = -1
	ans = ''
	for i in range(l):
		if b[i] == '2':
			ans = '0' * (l - i)
			ind = i
			break
	if ind == 0:
		ans = '1' + ans
	elif ind == -1:
		ans = b
	else:
		ind1 = -1
		for i in range(ind - 1, -1, -1):
			if b[i] == '1':
				ans = '0' + ans
			else:
				ans = '1' + ans
				ind1 = i
				break
		if ind1 == -1:
			ans = '1' + ans
		else:
			ans = b[0:ind1] + ans
	print(int(ans, 3))


import sys
input = sys.stdin.readline
Q = int(input())
Query = [int(input()) for _ in range(Q)]
for N in Query:
	A = []
	n = N
	while n > 0:
		A.append(n % 3)
		n //= 3
	last2 = -1
	last0 = {}
	for (i, a) in enumerate(A):
		if a == 2:
			last2 = i
		elif a == 0 and (not last2 in last0):
			last0[last2] = i
	if last2 == -1:
		B = A
	else:
		B = []
		if last2 in last0:
			d0 = last0[last2]
			for i in range(len(A)):
				if i < d0:
					B.append(0)
				elif i == d0:
					B.append(1)
				else:
					B.append(A[i])
		else:
			B = [0] * len(A) + [1]
	ans = 0
	dig = 1
	for b in B:
		ans += dig * b
		dig *= 3
	print(ans)


import math as m
q = int(input())
for _ in range(q):
	n = int(input())
	pow = m.log(n, 3)
	pceil = m.ceil(pow)
	pfloor = m.floor(pow)
	if pceil == pfloor:
		print(n)
		continue
	if n > (3 ** pceil - 1) / 2:
		print(3 ** pceil)
		continue
	sum = 3 ** pfloor
	i = pfloor - 1
	found = False
	sjumped = 0
	while i >= 0:
		if sum + 3 ** i > n:
			sjumped = sum + 3 ** i
			i -= 1
			continue
		if sum + 3 ** i == n:
			print(n)
			found = True
			break
		sum += 3 ** i
		i -= 1
	if found == False:
		print(sjumped)


def conv(n: int, b: int=3) -> int:
	a = 0
	p = 1
	while n:
		a += n % b * p
		p *= 10
		n //= b
	return a

def solve(n: int) -> int:
	p = 0
	s = ''
	while n:
		l = n % 10
		if p:
			l = (l + 1) % 3
			if l == 0:
				p = 1
				s += '0'
			elif l == 1:
				p = 0
				s = '0' * len(s) + '1'
			else:
				p = 1
				s += '0'
		elif l == 2:
			p = 1
			s += '0'
		else:
			p = 0
			s += str(l)
		n //= 10
	if p:
		s = '0' * len(s) + '1'
	return s[::-1]
for _ in range(int(input())):
	print(int(solve(conv(int(input()))), 3))


from math import log

def isa(n):
	sm = log(n, 3)
	if sm.is_integer():
		ans = 3 ** int(sm)
	else:
		sm = int(sm)
		sumt = 0
		for i in range(sm):
			sumt += 3 ** i
		if n - 3 ** sm > sumt:
			ans = 3 ** (sm + 1)
		else:
			ans = 3 ** sm
			temp = n - 3 ** sm
			ans += isa(temp)
	return ans
for _ in range(int(input())):
	n = int(input())
	print(isa(n))


q = int(input())
for i in range(q):
	n = int(input())
	arr = 10 ** 100
	flag = True
	for m in range(100):
		counter = 0
		while flag:
			for i in range(m, -1, -1):
				if counter + 3 ** i < n:
					counter += 3 ** i
					m -= 1
				else:
					flag = False
					arr = min(arr, counter + 3 ** i)
			break
	print(arr)


q = int(input())
while q > 0:
	q -= 1
	n = int(input())
	rems = []
	while n > 0:
		rems.append(n % 3)
		n = n // 3
	rems.append(0)
	rems = rems[::-1]
	for i in range(0, len(rems)):
		if rems[i] > 1:
			for j in range(i, len(rems)):
				rems[j] = 0
			rems[i - 1] += 1
			for j in range(i - 1, 0, -1):
				if rems[j] > 1:
					rems[j] = 0
					rems[j - 1] += 1
			break
	rems = rems[::-1]
	res = 0
	mult = 1
	for i in rems:
		if i == 1:
			res += mult
		mult *= 3
	print(res)


import math
for _ in range(int(input())):
	n = int(input())
	s = set()
	a = []
	su = 0
	n1 = n
	while su < n1:
		try:
			k = math.log(n, 3)
			k1 = int(k)
			k2 = int(math.ceil(k))
			cc = 3 ** k2
			if cc not in s:
				a.append(su + cc)
			lol = 3 ** k1
			if lol not in s:
				s.add(lol)
				su += lol
				if su >= n1:
					a.append(su)
					break
				n -= lol
			else:
				break
		except:
			break
	print(min(a))


import math

def main():
	q = int(input())
	for iter in range(q):
		n = int(input())
		log = int(math.log(n, 3))
		check = 3 ** (log + 1)
		if check < n * 2 + 1:
			print(check)
		elif check == n * 2 + 1:
			print(n)
		else:
			result = 3 ** log
			rest = n - result
			log -= 1
			while rest > 0:
				l = -1
				r = log
				while r - l > 1:
					mid = int((r + l) / 2)
					a = 3 ** (mid + 1)
					if a < rest * 2 + 1:
						l = mid
					else:
						r = mid
				result += 3 ** r
				rest = n - result
				log = r - 1
			print(round(result))
main()


import math
import sys
input = sys.stdin.readline
nu = 1
dic = {1: 0}
for i in range(1, 39):
	nu *= 3
	dic[nu] = i
for _ in range(int(input())):
	n = int(input())
	co = 0
	li = [60]
	flag = True
	while n:
		if n in dic:
			if li[-1] == dic[n]:
				flag = False
				break
			else:
				li.append(dic[n])
				co += 1
				break
		xx = int(math.log(n, 3))
		if li[-1] == xx:
			flag = False
			break
		else:
			li.append(xx)
			co += 1
			n -= 3 ** xx
	if flag:
		ans = 0
		for i in range(1, co + 1):
			ans += 3 ** li[i]
		print(ans)
	else:
		ans = 0
		for i in range(1, co + 1):
			if li[-i - 1] - li[-i] != 1:
				ans = 3 ** (li[-i] + 1)
				break
		for j in range(i + 1, co + 1):
			ans += 3 ** li[-j]
		print(ans)


foo = []
n = int(input())
for i in range(n):
	x = int(input())
	w = 3 ** 39
	q = x
	j = 40
	while q >= x:
		j -= 1
		q = 3 ** j
	q = 3 ** (j + 1)
	w = min(w, q)
	q = 3 ** j
	while q < x and j > 0:
		j -= 1
		q += 3 ** j
		if q >= x:
			w = min(w, q)
			q -= 3 ** j
	foo.append(w)
for i in foo:
	print(i)


import math
for _ in range(int(input())):
	n = int(input())
	s1 = 0
	while n >= 1:
		a = int(math.log(n, 3)) + 1
		s = (pow(3, a) - 1) // 2
		if n > s:
			s1 += pow(3, a)
			break
		elif n == s:
			s1 += s
			break
		else:
			n -= pow(3, a - 1)
			s1 += pow(3, a - 1)
	print(s1)


t = int(input())
for _ in range(t):
	n = int(input())
	i = 0
	while True:
		if pow(3, i) >= n:
			res = pow(3, i)
			break
		i += 1
	i -= 1
	num = 0
	res2 = []
	while i >= 0:
		num += pow(3, i)
		if num >= n:
			res2.append(num)
			num -= pow(3, i)
		i -= 1
	if len(res2) == 0:
		print(res)
	else:
		print(min(res, min(res2)))


def my_power(base, power):
	ans = 1
	while power > 0:
		if power % 2 != 0:
			ans *= base
		base = base * base
		power = power // 2
	return ans

def back_to_base_ten(ans_trans):
	observed_zero = False
	observe_one = False
	one_start = 0
	ans = 0
	for j in range(len(ans_trans)):
		if ans_trans[j] == 0 and (not observed_zero):
			observed_zero = True
			if j != 0:
				ans += my_power(3, one_start) * (my_power(3, j - one_start) - 1) // 2
			observe_one = False
		if ans_trans[j] == 1 and (not observe_one):
			observe_one = True
			one_start = j
			observed_zero = False
	if not observed_zero:
		ans += my_power(3, one_start) * (my_power(3, len(ans_trans) - one_start) - 1) // 2
	return ans

def find(c):
	d = c
	trans = []
	last_two_index = -1
	i = 0
	while d > 0:
		digit = d % 3
		if digit == 2:
			last_two_index = i
		i += 1
		trans.append(digit)
		d = d // 3
	ans_trans = []
	two_observed = False
	if last_two_index != -1:
		for i in range(len(trans)):
			done = False
			if not two_observed and i == last_two_index:
				two_observed = True
			if trans[i] == 0 and i > last_two_index and two_observed:
				two_observed = False
				ans_trans.append(1)
				done = True
			if not done:
				if i < last_two_index or two_observed:
					ans_trans.append(0)
				else:
					ans_trans.append(trans[i])
	else:
		ans_trans = trans
	if two_observed:
		ans_trans.append(1)
	ans = back_to_base_ten(ans_trans)
	return ans
ref = []
n = int(input())
for i in range(n):
	c = int(input())
	print(find(c))


from functools import reduce
import os
import sys
from collections import *
from math import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def arr():
	return [int(i) for i in input().split()]

def sarr():
	return [int(i) for i in input()]

def starr():
	return [str(x) for x in input().split()]

def inn():
	return int(input())

def svalue():
	return tuple(map(str, input().split()))

def parr():
	return [value() for i in range(n)]
mo = 1000000007
inf = 1e+18
div = 998244353
res = []
val = 1
for i in range(50):
	res += [val]
	val *= 3
for _ in range(inn()):
	n = inn()
	val = bisect_right(res, n)
	if sum(res[:val]) < n:
		print(res[val])
		continue
	val -= 1
	ans = inf
	sm = 0
	for i in range(val, -1, -1):
		if sm + res[i] >= n:
			ans = min(sm + res[i], ans)
		else:
			sm += res[i]
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = []
	b = [0]
	for i in range(50):
		a.append(3 ** i)
		b.append(b[-1] + a[-1])
		if b[-1] > n:
			break
	s = b[i + 1]
	a = a[::-1]
	for j in a:
		if s - j >= n:
			s -= j
	print(s)


q = int(input())
for i in range(q):
	n = int(input())
	powers = [1]
	a = powers[0]
	j = 1
	while n > a:
		powers.append(powers[j - 1] * 3)
		a = powers[j]
		j += 1
	start = len(powers) - 1
	if powers[start] > n:
		start -= 1
	represent = []
	temp = n
	for j in range(start, -1, -1):
		m = temp // powers[j]
		represent.append(m)
		temp -= powers[j] * m
	powers.reverse()
	start = -1
	for j in range(len(represent)):
		if represent[j] > 1:
			start = j
			break
	if start == 0 and powers[start] >= n:
		print(powers[0])
	elif start == 0 and powers[start] < n:
		print(powers[0] * 3)
	elif start == -1:
		print(n)
	else:
		result = 0
		index = -1
		for k in range(start, 0, -1):
			if represent[k] == 0:
				index = k
				break
		if index == -1 and powers[0] >= n:
			print(powers[0])
		elif index == -1 and powers[0] < n:
			print(powers[0] * 3)
		elif len(powers) != len(represent):
			for k in range(0, index):
				if powers[k + 1] > n:
					continue
				result += powers[k + 1] * represent[k]
			result += powers[index + 1]
			print(result)
		else:
			for k in range(0, index):
				if powers[k] > n:
					continue
				result += powers[k] * represent[k]
			result += powers[index]
			print(result)


def per(num):
	base = 3
	newNum = ''
	while num > 0:
		newNum = str(num % 3) + newNum
		num //= base
	return newNum
q = int(input())
for _ in range(q):
	n = int(input())
	n = per(n)
	n = '0' + n
	while n.find('2') != -1:
		n = n[0:n.find('2') - 1] + str(int(n[n.find('2') - 1]) + 1) + '0' * (len(n) - n.find('2'))
	print(int(n, 3))


def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(nums)

def solve():
	n = int(input())
	s = list(ternary(n))
	s.append('0')
	changed = False
	for i in range(len(s) - 2, -1, -1):
		if changed:
			s[i] = '0'
			continue
		if s[i] == '2':
			s[i] = '0'
			j = i + 1
			while s[j] == '1':
				j += 1
				s[j - 1] = '0'
			s[j] = '1'
			changed = True
	ans = list(reversed(s))
	ans1 = ''.join(ans)
	print(int(ans1, 3))
for _ in range(int(input())):
	solve()


import sys
input = lambda : sys.stdin.readline()
MOD = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : list(map(int, input().split()))
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
for _ in range(ii()):
	n = ii()
	x = n
	mn = 10 ** 12
	s = ''
	for i in range(50, -1, -1):
		if n >= 3 ** i:
			n -= 3 ** i
			s += '1'
		else:
			s += '0'
	if n != 0:
		s = bin(int(s, 2) + 1)[2:]
	num = 0
	pw = 0
	for i in s[::-1]:
		if i == '1':
			num += 3 ** pw
		pw += 1
	print(num)


def log3(x):
	(l, r) = (-1, 40)
	while r - l > 1:
		m = (r + l) // 2
		if 3 ** m > x:
			r = m
		else:
			l = m
	if l < 0:
		return r
	return l
t = int(input())
for _ in range(t):
	n = int(input())
	powers = [0] * 39
	while n > 0:
		p = log3(n)
		powers[p] += 1
		n -= 3 ** p
	prev = 0
	while prev < 38:
		ok = True
		for i in range(prev, 39):
			prev = i + 1
			if powers[i] > 1:
				powers[i + 1] += 1
				for j in range(i + 1):
					powers[j] = 0
				break
	a = 0
	for i in range(39):
		a += powers[i] * 3 ** i
	print(a)


def goodNumber(n):
	test = new_n = n
	remainder = count = 0
	while test:
		value = test % 3 + remainder
		if value > 1:
			remainder = 1
			new_n = 0
		else:
			remainder = 0
			if new_n != n and value:
				new_n += 3 ** count
		test //= 3
		count += 1
	return new_n if new_n else 3 ** count
for i in range(int(input())):
	print(goodNumber(int(input())))


for _ in range(int(input())):
	n = int(input())
	i = 1
	p = 0
	while p < n:
		p += i
		if i < n:
			i *= 3
		else:
			break
	while i > 0:
		if p - i >= n:
			p -= i
		i //= 3
	print(p)


def to_ternary(n):
	l = []
	while n > 0:
		y = n % 3
		l.append(y)
		n = n // 3
	return reversed(l)
for _ in range(int(input())):
	a = int(input())
	x = list(to_ternary(a))
	tw = False
	pos2 = -1
	pos0 = -1
	for i in range(len(x)):
		if x[i] == 2:
			tw = True
			pos2 = i
			break
		if x[i] == 0:
			pos0 = i
	if not tw:
		print(a)
	elif pos0 == -1:
		print(3 ** len(x))
	else:
		x[pos0] = 1
		t = len(x)
		s = 0
		for i in range(0, pos0 + 1):
			s += x[i] * 3 ** (len(x) - i - 1)
		print(s)


for _ in range(int(input())):
	n = int(input())
	o = n
	t = []
	while n > 1:
		if n % 3 == 0:
			t.append(0)
			n //= 3
			continue
		if n % 3 == 1:
			t.append(1)
			n //= 3
			continue
		if n % 3 == 2:
			n += 1
			n //= 3
			t.append(0)
	t.append(1)
	r = 3 ** (len(t) - 1)
	x = r
	for tt in t[-2::-1]:
		if r >= o:
			break
		x //= 3
		r += tt * x
	print(r)


for _ in range(int(input())):
	n = int(input())
	currsum = 1
	for i in range(1, 40):
		currsum += 3 ** i
	while i >= 0:
		if currsum - 3 ** i >= n:
			currsum -= 3 ** i
		i -= 1
	print(currsum)


def find_closest(num):
	sum_ = 0
	curr = 1
	degree = 0
	while sum_ < num:
		sum_ += curr
		curr *= 3
		degree += 1
	while degree != -1:
		if sum_ - curr >= num:
			sum_ -= curr
		curr = curr // 3
		degree -= 1
	return sum_
amount = int(input())
for i in range(amount):
	n = int(input())
	print(find_closest(n))


def toStr(n, base):
	convertString = '0123456789ABCDEF'
	if n < base:
		return convertString[n]
	else:
		return toStr(n // base, base) + convertString[n % base]

def ans(n):
	s = '0' + toStr(n, 3)
	if '2' in s:
		ind1 = s.find('2')
		s2 = s[:ind1]
		s3 = s[ind1:]
		num = s2[:s2.rfind('0')] + '1' + '0' * len(s2[s2.rfind('0') + 1:] + s3)
		return int(num, 3)
	else:
		return n
t = int(input())
for _ in range(t):
	print(ans(int(input())))


def tobase3(n):
	a = []
	while n > 0:
		a.append(n % 3)
		n //= 3
	a.reverse()
	return a

def todec(a):
	sum = 0
	for i in range(len(a)):
		sum *= 3
		sum += a[i]
	return sum
t = int(input())
for _ in range(t):
	n = int(input())
	a = tobase3(n)
	j = 0
	flag = False
	for i in range(len(a)):
		if a[i] == 2:
			flag = True
			j = i
			while j >= 0 and a[j] != 0:
				j -= 1
			break
	if j < 0 and flag:
		print(3 ** len(a))
	elif flag:
		print(todec(a[:j] + [1] + [0] * (len(a) - j - 1)))
	else:
		print(n)


def main():

	def cnv(n):
		if n == 0:
			return 0
		digits = []
		base = 3
		while n != 0:
			if n % base == 0:
				digits.append('0')
			elif n % base == 1:
				digits.append('1')
			else:
				digits.append('2')
			n //= base
		return ''.join(digits)

	def r_cnv(S):
		d = 1
		ret = 0
		carry = 0
		for s in S:
			v = int(s)
			if carry == 0:
				if v <= 1:
					ret += v * d
				else:
					carry = 1
			else:
				ret = d
				if v == 0:
					carry = 0
			d *= 3
		if carry:
			ret = d
		return ret
	Q = int(input())
	for _ in range(Q):
		N = int(input())
		S = cnv(N)
		print(r_cnv(S))
main()


q = int(input())
pp = [1]
ps = [1]
out = []
for _ in range(q):
	n = int(input())
	while pp[-1] < n:
		pp.append(3 * pp[-1])
		ps.append(ps[-1] + pp[-1])
	r = 0
	for i in range(len(pp) - 1, -1, -1):
		if r + pp[i] == n:
			r += pp[i]
			break
		elif r + pp[i] > n:
			if i == 0 or r + ps[i - 1] < n:
				r += pp[i]
				break
		elif r + ps[i - 1] < n:
			r += pp[i]
	out.append(r)
print('\n'.join(map(str, out)))


def gg(a):
	s = ''
	while a != 0:
		s += str(a % 3)
		a = a // 3
	return s

def gg1(a):
	k = 0
	for i in range(len(a)):
		k += int(a[i]) * 3 ** i
	return k
q = int(input())
for i in range(q):
	n = int(input())
	s = gg(n)
	j = s.rfind('2')
	if j == -1:
		print(n)
	else:
		h = s.find('0', j, len(s))
		if h == -1:
			s = '0' * len(s) + '1'
		else:
			s = '0' * h + '1' + s[h + 1:]
		print(gg1(s))


t = [1]
for i in range(40):
	t.append(t[-1] * 3)
t = t[::-1]
for _ in range(int(input())):
	z = n = int(input())
	a = []
	for i in t:
		a.append(n // i)
		n %= i
	i = 0
	while i < len(a):
		if a[i] not in [0, 1]:
			break
		i += 1
	i -= 1
	if i < 40:
		for j in range(i + 1, len(a)):
			a[j] = 0
		while i >= 0:
			if a[i] == 0:
				a[i] = 1
				break
			else:
				a[i] = 0
				i -= 1
				if i == -1:
					a.insert(0, 1)
					break
	print(int(''.join(map(str, a)), 3))


import sys
from collections import defaultdict, deque
from math import sqrt

def input():
	return sys.stdin.readline()[:-1]

def solve():
	n = int(input())
	on = n
	a = []
	while n:
		a.append(n % 3)
		n //= 3
	if 2 in a:
		a.append(0)
		j = 0
		for i in range(len(a)):
			if a[i] == 2:
				j = i
		for i in range(j, len(a)):
			if a[i] == 0:
				j = i
				break
		a[j] = 1
		for i in range(j):
			a[i] = 0
		ans = 0
		for i in range(len(a)):
			x = 3 ** i
			ans += x * a[i]
		print(ans)
	else:
		print(on)
t = int(input())
for _ in range(t):
	solve()


from sys import stdin, stdout
p3 = [1]
for i in range(41):
	p3 += [p3[-1] * 3]
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	trinary = ''
	n1 = n
	while n > 0:
		q = n // 3
		rem = n % 3
		trinary = str(rem) + trinary
		n //= 3
	trinary = '0' + trinary
	nn = len(trinary)
	pos2 = -1
	for i in range(nn):
		if trinary[i] == '2':
			pos2 = i
			break
	if pos2 == -1:
		print(n1)
		continue
	pp = pos2
	trinary = list(trinary)
	while trinary[pp] != '0':
		trinary[pp] = '0'
		pp -= 1
	trinary[pp] = '1'
	for i in range(pos2 + 1, nn):
		trinary[i] = '0'
	c = ans = 0
	for i in range(nn - 1, -1, -1):
		ans += p3[c] * int(trinary[i])
		c += 1
	print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import math
q = int(input())
a = []
u = int(math.log(10 ** 18)) + 2
for j in range(u):
	a.append(3 ** j)
a.reverse()
s = sum(a)
for i in range(q):
	ans = s
	n = int(input())
	for k in range(u):
		if ans - a[k] >= n:
			ans = ans - a[k]
	print(ans)


a = [3 ** i for i in range(40)]
for t in range(int(input())):
	n = int(input())
	x = sum(a)
	for i in a[::-1]:
		if x - i >= n:
			x -= i
	print(x)


from sys import stdin
q = int(stdin.readline().strip())
for _ in range(q):
	n = int(stdin.readline().strip())
	s = 0
	for i in range(n):
		s += 3 ** i
		if s >= n:
			break
	while s >= n and i >= 0:
		if s - 3 ** i >= n:
			s -= 3 ** i
		i -= 1
	print(s)


for _ in range(int(input())):
	n = int(input())
	val = 0
	i = 0
	while val <= n:
		val += pow(3, i)
		i += 1
	while i >= 0:
		if val - pow(3, i) >= n:
			val = val - pow(3, i)
		i -= 1
	print(val)


def ternary(x, ls):
	while x:
		ls.append(x % 3)
		x //= 3
	while len(ls) < 39:
		ls.append(0)
for _ in range(int(input())):
	n = int(input())
	ls = []
	ternary(n, ls)
	ls = ls[::-1]
	f = 0
	for i in ls:
		if i == 2:
			f = 1
	if f == 0:
		print(n)
	else:
		ind = -1
		for i in range(len(ls)):
			if ls[i] == 2:
				ind = i
				break
		cnt = -1
		for i in range(ind):
			if ls[i] == 0:
				cnt = i
		ls[cnt] = 1
		for i in range(cnt + 1, len(ls)):
			ls[i] = 0
		ans = 0
		for i in range(len(ls) - 1, -1, -1):
			ans += ls[i] * 3 ** (38 - i)
		print(ans)


q = int(input())
for i in range(q):
	n = int(input())
	a = 0
	i = 0
	while a < n:
		a += 3 ** i
		i += 1
	while i >= 0:
		if a - 3 ** i >= n:
			a -= 3 ** i
		i -= 1
	print(a)


import math

def check(n):
	max_pow = 50
	while n > 0:
		cur_pow = int(math.log(n, 3))
		if cur_pow == max_pow:
			return False
		max_pow = cur_pow
		n -= 3 ** cur_pow
	return True

def sum_rem(n):
	val = 3 ** (n + 1) - 1
	val /= 2
	return val

def missing_power(n, max_pow):
	n_init = n
	lmp = int(math.log(n, 3))
	cur_pow = 50
	pows = []
	val = 0
	for i in range(max_pow, -1, -1):
		if n >= 3 ** i:
			n -= 3 ** i
			pows.append(i)
			val += 3 ** i
		elif sum_rem(i - 1) >= n:
			continue
		else:
			val += 3 ** i
			return val
	return val
q = int(input())
while q > 0:
	n = int(input())
	if check(n):
		ans = n
	else:
		max_pow = int(math.log(n, 3))
		val = 3 ** (max_pow + 1) - 1
		val /= 2
		if n <= val:
			ans = missing_power(n, max_pow)
		else:
			ans = 3 ** (max_pow + 1)
	print(ans)
	q -= 1


a = [1]
p = 1
while p <= 10 ** 18:
	p = p * 3
	a.append(p)
a.append(p * 3)
for i in range(int(input())):
	n = int(input())
	ans = 1
	ind = -1
	for i in range(1, 40):
		if ans + a[i] <= n:
			ans += a[i]
		else:
			ans += a[i]
			ind = i
			break
	for i in range(ind, -1, -1):
		if ans - a[i] >= n:
			ans -= a[i]
	print(ans)


def f(n, x):
	ss = ''
	a = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
	b = []
	while True:
		s = n // x
		y = n % x
		b = b + [y]
		if s == 0:
			break
		n = s
	b.reverse()
	for i in b:
		ss += a[i]
	return ss
q = int(input())
for i in range(0, q):
	n = int(input())
	s = list(f(n, 3))
	l = len(s)
	ss = ''
	for i in range(l - 1, -1, -1):
		if s[i] == '1' or s[i] == '0':
			ss += s[i]
		else:
			ss += '0'
			s[i - 1] = str(ord(s[i - 1]) - ord('0') + 1)
	if s[0] == '2' or s[0] == '3':
		ss += '1'
	ans = 0
	ll = len(ss)
	if ll > l:
		ans += pow(3, ll - 1)
	else:
		for i in range(ll - 1, -1, -1):
			if ans >= n:
				break
			ans += pow(3, i) * (ord(ss[i]) - ord('0'))
	print(ans)


def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))

def toDec(a, base):
	ans = 0
	inc = 1
	while a:
		digit = inc * (a % 10)
		ans += digit
		a //= 10
		inc *= base
	return ans
for i in range(int(input())):
	y = int(input())
	a = ternary(y)
	i = a.count('2')
	if i > 0:
		t = a.index('2')
		r = a[0:t]
		q = r.count('0')
		if q > 0:
			for i in range(len(r) - 1, -1, -1):
				if r[i] == '0':
					z = int(a[:i] + '1' + '0' * (len(a) - 1 - i))
					print(toDec(z, 3))
					break
		else:
			d = int('1' + '0' * len(a))
			print(toDec(d, 3))
	else:
		print(y)


for _ in range(int(input())):
	n = int(input())
	(sumof_powers, max_power) = (1, 1)
	while sumof_powers < n:
		max_power *= 3
		sumof_powers += max_power
	while max_power != 0:
		if sumof_powers - max_power >= n:
			sumof_powers -= max_power
		max_power //= 3
	print(sumof_powers)


for _ in range(int(input())):
	n = int(input())
	tenary = []
	while n > 0:
		tenary.append(n % 3)
		n //= 3
	tenary = tenary[::-1]
	for i in range(len(tenary)):
		if tenary[i] == 2:
			pos_2 = i
			break
	if 2 not in tenary:
		print(int(''.join([str(i) for i in tenary]), 3))
		continue
	tenary[pos_2:] = [0] * (len(tenary) - pos_2)
	tenary.insert(0, 0)
	pos_0 = pos_2 + 1
	for i in range(pos_2, -1, -1):
		if tenary[i] == 0:
			pos_0 = i
			break
		else:
			pos_0 -= 1
	tenary[pos_0] = 1
	for i in range(pos_0 + 1, len(tenary)):
		tenary[i] = 0
	re = int(''.join([str(i) for i in tenary]), 3)
	print(re)


import math
x = eval(input())
j = 0
for i in range(x):
	a = 0
	y = eval(input())
	k = math.floor(math.log(y, 3))
	s = [0 for j in range(math.floor(math.log(y, 3)) + 2)]
	while y:
		z = math.floor(math.log(y, 3))
		s[k - z + 1] += 1
		y = y - 3 ** z
	z = -1
	b = 0
	t = 0
	for k in range(len(s)):
		if s[k] == 0:
			z = k
			b = 0
		elif s[k] == 1:
			a = a + 3 ** (len(s) - k - 1)
			b = b + 3 ** (len(s) - k - 1)
		else:
			t = 1
			break
	if t == 1:
		a = a + 3 ** (len(s) - z - 1) - b
	print(a)


def ter(n):
	l = []
	a = 0
	su = 0
	while n > 1:
		r = n % 2
		l.append(r)
		n = n // 2
	for e in l:
		su = su + int(3 ** a) * e
		a = a + 1
	return su

def sea(n):
	l = 0
	h = 1000000000000000001
	while l <= h:
		m = (l + h) // 2
		v1 = ter(m)
		v2 = ter(m + 1)
		if n == v1:
			return n
		elif n < v2 and n > v1:
			return v2
		elif n < v1:
			h = m - 1
		else:
			l = m + 1
q = int(input())
while q > 0:
	n = int(input())
	ans = sea(n)
	print(ans)
	q = q - 1


power = []
cur = 0
while 3 ** cur <= 10 ** 21:
	power.append(3 ** cur)
	cur += 1
sumall = [1]
for i in range(1, len(power)):
	sumall.append(sumall[-1] + power[i])
Q = int(input())
from bisect import *
for q in range(Q):
	n = int(input())
	pos = bisect_right(power, n)
	if power[pos] == n or sumall[pos - 1] < n:
		print(power[pos])
		continue
	can = sumall[pos - 1]
	for i in range(pos - 1, -1, -1):
		if can - power[i] >= n:
			can -= power[i]
	print(can)


q = int(input())

def maxpow3(x):
	cur = 0
	num = 1
	while num <= x:
		num *= 3
		cur += 1
	return num // 3
flag = 1
L = []
for que in range(q):
	n = int(input())
	L = []
	while n > 0:
		L.append(maxpow3(n))
		while len(L) > 1:
			if L[-1] == L[-2]:
				x = L[-1] * 3
				L.pop()
				L.pop()
				L.append(x)
			else:
				break
		n -= L[-1]
	print(sum(L))


import array
import math
import os
import sys

def main():
	Q = read_int()
	for _ in range(Q):
		N = read_int()
		print(solve(N))

def solve(N):
	s = []
	while N > 0:
		s.append(N % 3)
		N //= 3
	s.append(0)
	for i in range(len(s) - 1, -1, -1):
		if s[i] == 2:
			for j in range(0, i + 1):
				s[j] = 0
			j = i + 1
			while True:
				s[j] += 1
				if s[j] < 2:
					break
				s[j] = 0
				j += 1
			break
	a = 0
	d = 1
	for v in s:
		a += v * d
		d *= 3
	return a
DEBUG = 'DEBUG' in os.environ

def inp():
	return sys.stdin.readline().rstrip()

def read_int():
	return int(inp())

def read_ints():
	return [int(e) for e in inp().split()]

def dprint(*value, sep=' ', end='\n'):
	if DEBUG:
		print(*value, sep=sep, end=end)
main()


from sys import exit as sys_return
queries = int(input())
while queries != 0:
	queries -= 1
	number = int(input())
	(sum_of_powers, max_power) = (1, 1)
	while sum_of_powers < number:
		max_power *= 3
		sum_of_powers += max_power
	while max_power != 0:
		if sum_of_powers - max_power >= number:
			sum_of_powers -= max_power
		max_power //= 3
	print(sum_of_powers)


import math
for _ in range(int(input())):
	n = int(input())
	two = 0
	zero = 0
	temp = n
	bits = []
	while temp > 0:
		if temp % 3 == 2:
			two += 1
		if temp % 3 == 0:
			zero += 1
		bits.append(temp % 3)
		temp = temp // 3
	if two > 0 and zero > 0:
		x = 0
		for i in range(len(bits)):
			if bits[i] == 0:
				zero -= 1
			if bits[i] == 2:
				x = i
				two -= 1
			if two == 0:
				break
			else:
				bits[i] = 0
		if zero > 0:
			for i in range(x + 1, len(bits)):
				if bits[i] == 0:
					x = i
					bits[i] = 1
					break
				else:
					bits[i] = 0
		else:
			bits = [0] * (len(bits) + 1)
			bits[len(bits) - 1] = 1
	elif two > 0 and zero == 0:
		bits = [0] * (len(bits) + 1)
		bits[len(bits) - 1] = 1
	sm = 0
	for i in range(len(bits)):
		if bits[i] == 1:
			sm += 3 ** i
	print(int(sm))


cas = int(input())
while cas:
	cas -= 1
	n = int(input())
	initn = n
	ans = -1
	count = -1
	ls = []
	while n:
		count += 1
		if n % 3 == 2:
			ans = count
		ls.append(n % 3)
		n //= 3
	ls.append(0)
	if ans == -1:
		print(initn)
	else:
		poi = ans
		while ls[poi] != 0:
			poi += 1
		ls[poi] = 1
		for i in range(poi):
			ls[i] = 0
		finans = 0
		for i in range(len(ls)):
			finans += pow(3, i) * ls[i]
		print(finans)


tests = int(input())
bit = 60
for te in range(tests):
	n = int(input())
	arr = [0 for i in range(bit)]
	index = 0
	while n > 0:
		rem = n % 3
		arr[index] = rem
		index += 1
		n = n // 3
	last_index = -1
	for i in range(bit):
		if arr[i] == 2:
			last_index = i
	if last_index != -1:
		for j in range(last_index + 1, bit):
			if arr[j] == 0:
				first_index = j
				break
		for i in range(first_index):
			arr[i] = 0
		arr[first_index] = 1
	ans = 0
	count = 1
	for i in range(bit):
		ans += arr[i] * count
		count *= 3
	print(ans)


import sys
import bisect

def rint():
	return map(int, sys.stdin.readline().split())

def input():
	return sys.stdin.readline().rstrip('\n')

def oint():
	return int(input())

def bisect(i):
	pass
q = oint()
for _ in range(q):
	n = oint()
	mindiff = 10 ** 10
	ans = 0
	l = 1
	r = 2 ** 40
	while l < r:
		i = (l + r) // 2
		s = bin(i)[2:]
		ss = int(s, 3)
		if n <= ss:
			r = i
		elif n > ss:
			l = i + 1
	s = bin(r)[2:]
	ss = int(s, 3)
	print(ss)


q = int(input())
for i in range(q):
	n = int(input())
	temp = n
	ternary = ''

	def base_3(n):
		global ternary
		while n > 0:
			ternary += str(n % 3)
			n = n // 3
		ternary = ternary[-1::-1]
		return ternary

	def base_10(s):
		b10 = 0
		power = len(s)
		for j in s:
			b10 += int(j) * 3 ** (power - 1)
			power -= 1
		return b10
	while '2' in base_3(n):
		l = len(ternary)
		index = ternary.index('2')
		n = temp + 3 ** (l - index - 1) - base_10(ternary[index + 1:])
		temp = n
		ternary = ''
	print(n)


for _ in range(int(input())):
	n = int(input())
	digits = []
	n_0 = n
	while n_0:
		digits.append(n_0 % 3)
		n_0 //= 3
	digits.reverse()
	for i in range(len(digits)):
		if digits[i] == 2:
			for j in range(i, len(digits)):
				digits[j] = 0
			idx = i - 1
			while idx >= 0 and digits[idx] == 1:
				digits[idx] = 0
				idx -= 1
			if idx < 0:
				digits.insert(0, 1)
			else:
				digits[idx] += 1
			print(int(''.join(map(str, digits)), 3))
			break
	else:
		print(n)


import sys
input = sys.stdin.readline
from math import ceil, log10
t = int(input())
for _ in range(t):
	n = int(input())
	lis = []
	while n > 0:
		lis.append(n % 3)
		n //= 3
	lis.append(0)
	last = 0
	for i in range(len(lis) - 1, -1, -1):
		if lis[i] == 2:
			last = i
			break
	ans = 0
	for i in range(last, len(lis)):
		if lis[i] == 2:
			lis[i] = 0
			lis[i + 1] += 1
		ans += lis[i] * 3 ** i
	print(ans)


import math
for _ in range(int(input())):
	n = int(input())
	from collections import deque
	a = deque()
	while n != 0:
		d = n % 3
		a.appendleft(d)
		n //= 3
	flag = 1
	lol = -1
	k = 0
	while flag == 1:
		flag = 0
		for j in range(len(a)):
			if a[j] == 2:
				if k == 0:
					if j == 0:
						lol = 1
					else:
						lol = j
				flag = 1
				if j == 0:
					a[j] = 0
					a.appendleft(1)
				else:
					a[j] = 0
					a[j - 1] += 1
				break
		k += 1
	if lol != -1:
		for j in range(lol, len(a)):
			a[j] = 0
	val = 0
	for j in range(len(a)):
		val += 3 ** (len(a) - j - 1) * a[j]
	print(val)


def ter(n):
	if n == 0:
		return 0
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(r)
	return nums

def solve():
	n = int(input())
	s = ter(n)
	s = s + [0]
	two = len(s) - 1 - s[::-1].index(2) if 2 in s else -1
	if two > -1:
		zero = s.index(0, two + 1, len(s))
		s[zero] = 1
		s[:zero] = [0] * zero
	s = ''.join(reversed(list(map(str, s))))
	print(int(s, 3))

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		solve()
main()


import sys
input = sys.stdin.readline
q = int(input())
pow3 = [1]
for _ in range(50):
	pow3.append(3 * pow3[-1])
for _ in range(q):
	n = int(input())
	s = []
	while n:
		x = n % 3
		s.append(x)
		n -= x
		n //= 3
	l = len(s)
	s.append(0)
	f = 0
	for i in range(l - 1, -1, -1):
		if f:
			s[i] = 0
		elif s[i] == 2:
			f = 1
			j = i
			while s[j]:
				s[j] = 0
				j += 1
			s[j] = 1
	ans = 0
	for i in range(l + 1):
		ans += s[i] * pow3[i]
	print(ans)


def cba(n):
	k = []
	d = n
	m = int(log(n, 3))
	while m >= 0:
		x = pow(3, m)
		if x <= n:
			k.append(m)
			n -= x
		m -= 1
	k.reverse()
	c = 0
	n = d - n
	for i in k:
		if i == c:
			n -= pow(3, c)
		else:
			n += pow(3, c)
			break
		c += 1
	return n

def abc(n):
	m = int(log(n, 3))
	while m >= 0:
		x = pow(3, m)
		if x <= n:
			n -= x
		m -= 1
	if n == 0:
		return 1
	return 0
from math import log
t = int(input())
for _ in range(t):
	n = int(input())
	i = n
	m = int(log(n, 3)) + 1
	x = (pow(3, m) - 1) // 2
	if n > x:
		print(pow(3, m))
	else:
		x = abc(n)
		if x:
			print(n)
		else:
			print(cba(n))


from sys import stdin
input = stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	k = n
	z = []
	while k > 0:
		r = k % 3
		z.append(r)
		k //= 3
	z.append(0)
	z.reverse()
	if not 2 in z:
		print(n)
		continue
	a = z.index(2)
	b = -1
	for i in range(a, -1, -1):
		if z[i] == 0:
			b = i
			break
	z[b] = 1
	for i in range(b + 1, len(z)):
		z[i] = 0
	ans = 0
	power = 1
	for i in range(len(z) - 1, -1, -1):
		ans += z[i] * power
		power *= 3
	print(ans)


q = int(input())
for _ in range(q):
	n = int(input())
	s = ''
	while n > 0:
		s = chr(n % 3 + ord('0')) + s
		n = n // 3
	if s[0] == '2':
		m = 3 ** len(s)
	else:
		if s.count('2') > 0:
			j = s.index('2')
			if s.count('0') > 0 and s.index('0') < j:
				k = j - 1
				while s[k] != '0':
					k -= 1
				s = s[:k] + '1' + '0' * (len(s) - k - 1)
			else:
				s = '1' + '0' * len(s)
		m = ord(s[0]) - ord('0')
		for i in range(1, len(s)):
			m = m * 3 + ord(s[i]) - ord('0')
	print(m)


def log3(x):
	exp = 0
	power = 1
	while power * 3 < x:
		power *= 3
		exp += 1
	return exp

def next_exp(x):
	cur_exp = log3(x)
	return cur_exp + 1

def prev_exp(x):
	cur_exp = log3(x)
	return cur_exp

def median(x):
	return (3 ** next_exp(x) - 1) // 2

def print_good():
	n = int(input())
	m = 0
	for i in range(100):
		if n == 1:
			m += 1
			print(m)
			return 0
		if n > median(n):
			m += 3 ** next_exp(n)
			print(m)
			return 0
		m += 3 ** prev_exp(n)
		n -= 3 ** prev_exp(n)
	return 0

def main():
	q = int(input())
	for i in range(q):
		print_good()
main()


l = [3 ** i for i in range(0, 40)]
s = sum(l)
for i in range(int(input())):
	n = int(input())
	ts = s
	for j in l[::-1]:
		if ts - j >= n:
			ts -= j
	print(ts)


from sys import stdin
from collections import defaultdict
t = int(stdin.readline())
pow3 = []
x = 1
while x <= 1e+19:
	pow3.append(x)
	x = x * 3
for _ in range(t):
	n = int(stdin.readline())
	for i in range(len(pow3)):
		if pow3[i] >= n:
			idx = i
			break
	if pow3[idx] == n:
		print(n)
		continue
	bestAnswer = 1e+20
	change = False
	for i in range(idx - 1, -1, -1):
		currentSum = pow3[i]
		for j in range(i - 1, -1, -1):
			if currentSum + pow3[j] >= n:
				if currentSum + pow3[j] < bestAnswer:
					bestAnswer = currentSum + pow3[j]
					change = True
			else:
				currentSum = currentSum + pow3[j]
	if not change:
		print(pow3[idx])
	else:
		print(bestAnswer)


q = int(input())
for i in range(q):
	n = int(input())
	s = ''
	while n > 0:
		s += str(n % 3)
		n //= 3
	s = s[::-1]
	j = 0
	j2 = -1
	i0 = -1
	while j < len(s):
		if s[j] == '0':
			i0 = j
		elif s[j] == '2':
			j2 = j
			break
		j += 1
	if j2 != -1:
		if i0 == -1:
			s = '1' + '0' * len(s)
		else:
			s = s[:i0] + '1' + '0' * (len(s) - i0 - 1)
	print(int(s, 3))


q = int(input())
for i in range(q):
	n = int(input())

	def base3(n):
		out = []
		num = n
		while num > 0:
			out.append(num % 3)
			num = num // 3
		return out

	def base10(arr):
		num = 0
		for j in range(len(arr)):
			num += 3 ** j * arr[j]
		return num
	b3 = base3(n)
	last2 = -1
	for j in range(len(b3) - 1, -1, -1):
		if b3[j] == 2:
			last2 = j
			break
	if last2 == -1:
		print(base10(b3))
	else:
		first0 = len(b3)
		for j in range(last2 + 1, len(b3)):
			if b3[j] == 0:
				first0 = j
				break
		for j in range(first0):
			b3[j] = 0
		if first0 != len(b3):
			b3[first0] = 1
		else:
			b3.append(1)
		ans = base10(b3)
		print(ans)


def run_on_file(filename):
	with open(filename, 'r') as f:
		for line in f:
			n = int(line)
			good_number(n)

def run_on_input():
	nq = int(input())
	for i in range(nq):
		n = int(input())
		good_number(n)

def good_number(n: int):
	base = 3
	candidates = [base ** 0]
	i = 0
	while base ** i <= n:
		i += 1
		candidates.append(base ** i)
	target = n
	choices = []
	while target > 0:
		(lower, upper) = binary_search_range(candidates, target)
		lower_sum = sum(candidates[:lower + 1])
		if lower_sum >= target:
			choices.append(candidates[lower])
			target -= candidates[lower]
		else:
			choices.append(candidates[upper])
			target -= candidates[upper]
	print(sum(choices))

def binary_search_range(array, target):
	lower = 0
	upper = len(array) - 1
	while lower < upper:
		middle = (lower + upper) // 2
		middle_value = array[middle]
		if target > middle_value:
			adjacent = middle + 1
			if target < array[adjacent]:
				return (middle, adjacent)
			else:
				lower = middle + 1
		elif target < middle_value:
			adjacent = middle - 1
			if target > array[adjacent]:
				return (adjacent, middle)
			else:
				upper = middle
		else:
			return (middle, middle)
run_on_input()


q = int(input())
for _ in range(q):
	n = int(input())
	c = []
	while n > 0:
		c.append(n % 3)
		n = n // 3
	d = 0
	s = 0
	for i in range(len(c)):
		x = c[i] + d
		if x == 0 or x == 1:
			s += x * pow(3, i)
			d = 0
		else:
			s = 0
			d = 1
	if d == 1:
		s = pow(3, i + 1)
	print(s)


import sys
line_count = 0
for line in sys.stdin.readlines():
	inputs = line.split()
	if line_count == 0:
		q = int(inputs[0])
	else:
		n = int(inputs[0])
		res = n
		power = 1
		ternary = []
		pos = 0
		highest_pos = -1
		while True:
			if res == 0:
				break
			(res, rem) = divmod(res, 3)
			if rem == 2:
				highest_pos = pos
				highest_power = power
			ternary.append(rem)
			power *= 3
			pos += 1
		ternary.append(0)
		m = 0
		start = False
		if highest_pos == -1:
			m = n
		else:
			for i in range(highest_pos + 1, len(ternary)):
				highest_power *= 3
				if ternary[i] == 0 and (not start):
					start = True
					m += highest_power
				if start:
					m += highest_power * ternary[i]
		print(m)
	if line_count == q:
		break
	line_count += 1


mx = int(1e+18)
cur = 1
c = 1
member = []
while cur <= mx:
	c += 1
	member.append(cur)
	cur *= 3
member.append(cur)
n = len(member)
for _ in range(int(input())):
	visited = [0 for _ in range(n)]
	s = 0
	need = int(input())
	temp = 0
	for r in range(n - 1, -1, -1):
		idex = -1
		if not visited[r]:
			if s + member[r] < need:
				s += member[r]
				visited[r] = 1
			else:
				temp = s + member[r]
	if temp >= need:
		print(temp)
	else:
		print(member[-1])


import sys, bisect
input = sys.stdin.readline

def One(type):
	return type(input())

def List(type):
	return list(map(type, input().split()))

def Str():
	ans = list(input())
	ans.pop()
	return ans

def Many(type):
	return map(type, input().split())
vals = []
pows = []

def setVals():
	cur = s = 1
	while cur < 1e+18:
		vals.append(s)
		pows.append(cur)
		cur *= 3
		s += cur
	vals.append(s)
	pows.append(cur)

def solve():
	global vals
	n = One(int)
	cur = pows.copy()
	ind = bisect.bisect_left(vals, n)
	dif = vals[ind] - n
	ans = vals[ind]
	while dif > 0:
		ind = bisect.bisect(cur, dif) - 1
		if ind < 0:
			break
		dif -= cur[ind]
		ans -= cur[ind]
		cur.pop(ind)
	print(ans)

def main():
	t = One(int)
	setVals()
	for _ in range(t):
		solve()
main()


q = int(input())
for k in range(q):
	a = [int(0)] * 100
	n = int(input())
	ans = n
	tot = int(0)
	while n != 0:
		a[tot] = n % 3
		tot += 1
		n //= 3
	a[tot] = 0
	yes = True
	bit = 0
	for i in range(tot - 1, -1, -1):
		if a[i] == 2:
			yes = False
			bit = i
			break
	if yes:
		print(ans)
		continue
	for i in range(bit + 1, tot + 1):
		if a[i] == 0:
			a[i] = 1
			bit = i
			break
	ans = 0
	for i in range(tot, bit - 1, -1):
		ans = ans * 3 + a[i]
	ans = ans * 3 ** bit
	print(ans)


import math

def gcd(a, b):
	return a if b == 0 else gcd(b, a % b)

def lcd(a, b):
	return a * b // gcd(a, b)

def input_int():
	return list(map(int, input().split()))

def solve():
	s = 0
	[n] = input_int()
	for val in pl:
		if n >= val:
			s += val
			n -= val
		elif (val - 1) // 2 < n:
			s += val
			break
	print(s)
	return
[q] = input_int()
pl = [1]
for i in range(1, 39):
	pl.append(pl[i - 1] * 3)
pl.reverse()
for _ in range(0, q):
	solve()


for _ in range(int(input())):
	n = int(input())
	a = []
	while n:
		a += (n % 3,)
		n //= 3
	c = 0
	for i in range(len(a)):
		a[i] += c
		if 2 == a[i]:
			c = 1
			for j in range(i + 1):
				a[j] = 0
		elif a[i] > 2:
			a[i] = 0
			c = 1
		else:
			c = 0
	a += (c,)
	ans = 0
	for i in range(len(a) - 1, -1, -1):
		ans = ans * 3 + a[i]
	print(ans)


sq = []
x = 1
for i in range(40):
	sq.append(x)
	x *= 3
q = int(input())
for i in range(q):
	n = int(input())
	idx = 0
	for v in sq:
		idx += 1
		if v > n:
			break
	ss = sum(sq[:idx])
	if n > ss:
		print(sq[idx])
		continue
	d = ss - n
	idx = 0
	for v in sq:
		if v > d:
			break
		idx += 1
	while idx >= 0:
		if d >= sq[idx]:
			d -= sq[idx]
		idx -= 1
	print(n + d)


def get(x):
	s = ''
	while x:
		s += str(x % 3)
		x //= 3
	return s[::-1]
for _ in range(int(input())):
	n = int(input())
	s = get(n)
	s = '00' + s
	if s.count('2') == 0:
		print(n)
	else:
		f = s.find('2')
		while f >= 0 and s[f] != '0':
			f -= 1
		t = s[:f] + '1'
		f += 1
		while f < len(s):
			t += '0'
			f += 1
		print(int(t, 3))


def decTo3(num):
	rem = thNum = 0
	i = 1
	while num != 0:
		rem = num % 3
		num = num // 3
		thNum += rem * i
		i *= 10
	return thNum
t = int(input())
for k in range(t):
	x = int(input())
	x = str(decTo3(x))
	sum = 0
	searchForZero = False
	for i in range(len(x) - 1, -1, -1):
		if not searchForZero:
			if x[i] == '1':
				sum += 3 ** (len(x) - i - 1)
			if x[i] == '2':
				searchForZero = True
		else:
			sum = 0
			if x[i] == '0':
				sum += 3 ** (len(x) - i - 1)
				searchForZero = False
	if not searchForZero:
		print(sum)
	else:
		print(3 ** len(x))


def f(a):
	u = bin(a)
	u = u[2:]
	u = u[::-1]
	b = 0
	for i in range(len(u)):
		if u[i] == '1':
			b += pow(3, i)
	return b
q = int(input())
for i in range(q):
	n = int(input())
	(low, high) = (0, 1 << 40)
	ans = 0
	while low <= high:
		mid = int((low + high) / 2)
		x = f(mid)
		if x >= n:
			ans = x
			high = mid - 1
		else:
			low = mid + 1
	print(ans)


import math, bisect

def good(n):
	powers = set()
	while n > 0:
		x = int(math.log(n, 3))
		n -= 3 ** x
		if x not in powers:
			powers.add(x)
		else:
			return False
	return True

def pre():
	good_nums = []
	for i in range(1, 10 ** 6 + 1):
		if good(i):
			good_nums.append(i)
	return good_nums

def solve(n):
	powers = []
	while True:
		x = int(math.log(n, 3))
		if not powers:
			powers.append(x)
			n -= 3 ** x
		elif powers[-1] == x:
			curr = x
			powers.pop()
			while powers and powers[-1] == curr + 1:
				curr += 1
				powers.pop()
			powers.append(curr + 1)
			n = 0
			break
		else:
			n -= 3 ** x
			powers.append(x)
		if n <= 0:
			break
	ans = 0
	for i in powers:
		ans += 3 ** i
	print(ans)

def main():
	q = int(input())
	for i in range(q):
		n = int(input())
		solve(n)
main()


for i in range(int(input())):
	n = int(input())
	s = [0] + [3 ** i for i in range(40)]
	a = sum(s)
	for i in range(40, -1, -1):
		if a - s[i] >= n:
			a -= s[i]
	print(a)


import sys
import math
import itertools
import collections

def getdict(n):
	d = {}
	if type(n) is list or type(n) is str:
		for i in n:
			if i in d:
				d[i] += 1
			else:
				d[i] = 1
	else:
		for i in range(n):
			t = ii()
			if t in d:
				d[t] += 1
			else:
				d[t] = 1
	return d

def divs(n, start=1):
	r = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				r.append(i)
			else:
				r.extend([i, n // i])
	return r

def cdiv(n, k):
	return n // k + (n % k != 0)

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(map(int, input().split()))

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def wr(arr):
	return ''.join(map(str, arr))

def revn(n):
	return int(str(n)[::-1])

def prime(n):
	if n == 2:
		return True
	if n % 2 == 0 or n <= 1:
		return False
	sqr = int(math.sqrt(n)) + 1
	for d in range(3, sqr, 2):
		if n % d == 0:
			return False
	return True

def tr(number, base=3):
	newnumber = ''
	while number > 0:
		newnumber = str(number % base) + newnumber
		number //= base
	return newnumber
q = ii()
for _ in range(q):
	n = ii()
	s = list(tr(n))
	if '2' in s:
		pos2 = s.index('2')
		pos0 = 0
		for i in range(pos2, -1, -1):
			if s[i] == '0':
				pos0 = i
				break
		if pos0 != 0:
			s[pos0] = '1'
			for i in range(pos0 + 1, len(s)):
				s[i] = '0'
		else:
			s = '1' + '0' * len(s)
	ans = 0
	p = len(s)
	for i in range(p):
		ans += int(s[i]) * 3 ** (p - 1 - i)
	print(ans)


def ceillog(num, base):
	n = num
	res = 0
	while n:
		n //= base
		res += 1
	return res
t = int(input())
while t:
	t -= 1
	n = int(input())
	maxx = ceillog(n, 3)
	p = []
	for i in range(maxx + 1):
		p.append(3 ** i)
	chk = sum(p)
	while chk > n and p:
		if chk - p[-1] < n:
			p.pop()
		else:
			chk -= p[-1]
			p.pop()
	print(chk)


def ternary(n):
	while n:
		if n % 3 == 2:
			return 0
		n //= 3
	return 1

def ternary2(n):
	ans = []
	while n:
		ans.append(n % 3)
		n //= 3
	return ans + [0]
for _ in range(int(input())):
	n = int(input())
	if ternary(n):
		print(n)
	else:
		l = ternary2(n)
		flag = -1
		for i in range(len(l) - 1, -1, -1):
			if l[i] == 2:
				flag = i
				break
		for i in range(flag):
			l[i] = 0
		for i in range(flag, len(l)):
			if l[i] >= 2:
				l[i] = 0
				l[i + 1] += 1
		l = list(map(str, l))
		print(int(''.join(l)[::-1], 3))


import math
test = int(input())
for _ in range(test):
	n = int(input())
	up = int(math.log(n, 3))
	used = {}
	ans = 0
	while n > 0:
		rem = int(math.log(n, 3))
		if not used.get(rem, False):
			used[rem] = True
			n = n - 3 ** rem
			ans += 3 ** rem
		else:
			don = False
			for i in range(rem + 1, up):
				if not used.get(i, False):
					ans += 3 ** i
					for j in range(i - 1, -1, -1):
						if used.get(j, False):
							ans -= 3 ** j
					don = True
					break
			if not don:
				ans = 3 ** (up + 1)
				don = True
			break
	print(ans)


import math
v = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467, 3486784401, 10460353203, 31381059609, 94143178827, 282429536481, 847288609443, 2541865828329, 7625597484987, 22876792454961, 68630377364883, 205891132094649, 617673396283947, 1853020188851841, 5559060566555523, 16677181699666569, 50031545098999707, 150094635296999121, 450283905890997363, 1350851717672992089]
q = int(input())
for i in range(q):
	c = int(input())
	maior = id = int(math.log(c) / math.log(3)) + 1
	valor = c
	soma = 0
	while id >= 0 and valor <= (v[id] - 1) / 2:
		if valor - v[id - 1] >= 0:
			valor -= v[id - 1]
			soma += v[id - 1]
		id -= 1
	if valor > (v[id] - 1) / 2:
		soma += v[id]
		print(soma)
	else:
		print(soma)


pow3s = []
for i in range(39):
	pow3s.append(int(pow(3, i)))
n = int(input())
for i in range(n):
	x = int(input())
	p = 0
	j = 0
	while p < x:
		p += pow3s[j]
		j += 1
	j -= 1
	prev = p
	while p > x and j >= 0:
		p = p - pow3s[j]
		if p < x:
			p = p + pow3s[j]
			j -= 1
		else:
			j -= 1
	print(p)


import sys
from collections import defaultdict
input = sys.stdin.readline
lis = [1]
for i in range(1, 40):
	lis.append(lis[-1] * 3)
for _ in range(int(input())):
	n = int(input())
	s = 0
	i = 0
	while s < n:
		s += lis[i]
		i += 1
	if s == n:
		print(n)
		continue
	i -= 1
	while i >= 0:
		if s - lis[i] >= n:
			s -= lis[i]
		i -= 1
	print(s)


pows = [1] * 40
for i in range(1, 40):
	pows[i] = pows[i - 1] * 3
for _ in range(int(input())):
	n = int(input())
	m = sum(pows)
	for i in pows[::-1]:
		if m - i >= n:
			m -= i
	print(m)


for case in range(int(input())):
	n = int(input())
	k = 1
	while k < n:
		k *= 3
	if k >> 1 >= n:
		k >>= 1
		dif = k - n
		e = []
		while dif > 0:
			e.append(dif % 3)
			dif //= 3
		e = e[::-1]
		flag = False
		for i in range(len(e)):
			if e[i] > 1:
				flag = True
			if flag and e[i] == 0:
				e[i] = 1
		e = e[::-1]
		p = 1
		for it in e:
			if it:
				k -= p
			p *= 3
	print(k)


q = int(input())

def binPow(a, b):
	res = -1
	while b:
		if b & 1:
			res *= a
		a *= a
		b >>= 1
	return abs(res)
for w in range(q):
	n = int(input())
	m = 0
	stepen = 0
	if n == 1:
		print(1)
		continue
	while n > m:
		m += binPow(3, stepen)
		stepen += 1
	while stepen >= 0:
		if m - binPow(3, stepen) >= n:
			m -= binPow(3, stepen)
		stepen -= 1
	print(m)


q = int(input())
for fwewfe in range(q):
	n = int(input())
	sk = 1
	su = 0
	while su < n:
		su += sk
		sk *= 3
	while su >= n and sk > 0:
		if su - sk >= n:
			su -= sk
		sk //= 3
	print(su)


def find_next_num(x, powers_3):
	for (i, n) in enumerate(powers_3):
		if x == n:
			return x
		if n > x:
			cn = powers_3[i - 1]
			nn = find_next_num(x - cn, powers_3)
			if cn == nn:
				return n
			if nn > cn:
				return n
			return cn + nn
parr = [3 ** x for x in range(40)]
for _ in range(int(input())):
	print(find_next_num(int(input()), parr))


import sys
from os import path
from bisect import bisect_left as bl
from collections import Counter
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
import math
a = [3 ** i for i in range(40)]
t = int(input())
while t:
	t -= 1
	n = int(input())
	x = sum(a)
	for i in a[::-1]:
		if x - i >= n:
			x -= i
	print(x)


import os
import sys
from io import BytesIO, IOBase

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = int(input())
while t:
	n = int(input())
	orig = n
	l = []
	pos = -1
	while n > 0:
		l.append(n % 3)
		if l[-1] == 2:
			pos = len(l) - 1
		n //= 3
	if pos == -1:
		print(orig)
	else:
		i = 0
		for i in range(pos, len(l)):
			if l[i] == 0:
				l[i] = 1
				break
		if i == len(l) - 1:
			print(pow(3, len(l)))
		else:
			for j in range(0, i):
				l[j] = 0
			count = 0
			ans = 0
			for i in l:
				ans += i * pow(3, count)
				count += 1
			print(ans)
	t -= 1


t = int(input())
for _ in range(t):
	n = int(input())
	ans = ''
	c = -1
	nc = n
	nc2 = n
	while n != 0:
		n //= 3
		c += 1
	tmp = 3 ** c
	for i in range(c + 1):
		if tmp <= nc:
			ans += '1'
			nc -= tmp
		else:
			ans += '0'
		tmp //= 3
	i = len(ans) - 1
	k = 0
	ck = True
	res = ''
	while i >= 0:
		if ans[i] == '0':
			ck = False
			k = i
			break
		i -= 1
	comp = int(ans, 3)
	if comp != nc2:
		if ck:
			nc2 = 3 ** len(ans)
		else:
			res += ans[:k]
			res += '1'
			for i in range(k + 1, len(ans)):
				res += '0'
			nc2 = int(res, 3)
	print(nc2)


t = int(input())
for i in range(t):
	n = int(input())
	s = 0
	p = 0
	while s < n:
		s += 3 ** p
		p += 1
	while p >= 0:
		if s - 3 ** p >= n:
			s -= 3 ** p
		p -= 1
	print(s)


for _ in range(int(input())):
	n = int(input())
	d = []
	while n:
		(n, r) = divmod(n, 3)
		d.append(r)
	d.append(0)
	d.reverse()
	for i in range(1, len(d)):
		if d[i] == 2:
			d[i:] = [0] * (len(d) - i)
			d[i - 1] += 1
			for j in reversed(range(1, i)):
				if 1 < d[j] < 4:
					d[j] = 0
					d[j - 1] += 1
			break
	print(int(''.join(map(str, d)), 3))


import math
for _ in range(int(input())):
	x = int(input())
	pows = [1]
	ans = 1
	p = 1
	while True:
		p *= 3
		pows.append(p)
		ans += p
		if p > x:
			break
	for y in reversed(pows):
		if ans - y >= x:
			ans -= y
	print(ans)


import sys
q = int(sys.stdin.readline())
for _ in range(q):
	n = int(sys.stdin.readline())
	stack = []
	temp = n
	while temp != 0:
		stack.append(temp % 3)
		temp = temp // 3
	stack.reverse()
	stack = list(map(int, stack))
	if stack[0] == 2:
		stack = [1] + [0] * len(stack)
	else:
		judge = False
		is_two = False
		for i in range(1, len(stack)):
			if stack[i] == 2:
				is_two = True
				for j in range(i, -1, -1):
					if stack[j] == 0:
						stack[j] = 1
						stack = stack[:j + 1] + [0] * (len(stack) - j - 1)
						judge = True
						break
				break
		if judge == False and is_two == True:
			stack = [1] + [0] * len(stack)
	power = len(stack) - 1
	m = 0
	for j in range(len(stack)):
		m += stack[j] * 3 ** power
		power -= 1
	print(m)


import math

def calcular(contador, indice, numero):
	contador = 3 ** indice + contador
	if contador == numero:
		return contador
	elif contador > numero:
		if 3 ** indice - numero >= 0:
			return 3 ** indice
		else:
			return calcular(0, 0, abs(numero - 3 ** indice)) + 3 ** indice
	else:
		return calcular(contador, indice + 1, numero)
n = int(input())
for i in range(n):
	m = int(input())
	print(calcular(0, 0, m))


def task_3(n):
	division = n
	result = list()
	while division > 0:
		balance = division % 3
		division = division // 3
		result.append(balance)
	if 2 not in result:
		print(n)
	else:
		result.append(0)
		for (key, value) in enumerate(result):
			if value >= 2:
				result[0:key] = [0] * key
				result[key] = 0
				result[key + 1] += 1
		result_value = 0
		for (key, value) in enumerate(result):
			result_value += value * 3 ** key
		print(result_value)
q = int(input())
for q in range(q):
	(n,) = map(int, input().rstrip().split())
	task_3(n)


def maxM1(n):
	for x in range(0, n):
		if 3 ** x == n:
			return int(x)
		elif 3 ** x > n:
			return x - 1

def maxM(n):
	for x in range(0, n):
		if 3 ** x == n:
			return int(x)
		elif x == 0 and 3 ** x >= n:
			return 0
		elif 3 ** x > n:
			return int(x - 1)
for _ in range(int(input())):
	num = int(input())
	mxM = maxM(num)
	ans = 3 ** mxM
	li = []
	for i in range(mxM - 1, -1, -1):
		if ans >= num:
			break
		if ans + 3 ** i <= num:
			ans += 3 ** i
		else:
			x = ans
			x += 3 ** i
			li += [x]
	if ans == num:
		print(ans)
	elif not li:
		print(3 ** (mxM + 1))
	else:
		print(min(min(li), 3 ** (mxM + 1)))


l = [3 ** i for i in range(0, 40)]
k = sum(l)
for _ in range(int(input())):
	n = int(input())
	x = k
	for p in l[::-1]:
		if x - p >= n:
			x -= p
	print(x)


for q in range(int(input())):
	n = int(input())
	(pos2, val) = (-1, [])
	while n:
		i = n % 3
		val.append(i)
		if i == 2:
			pos2 = len(val) - 1
		n //= 3
	val.append(0)
	if pos2 != -1:
		pos0 = val[pos2:].index(0) + pos2
		val[pos0] = 1
		for i in range(pos0 - 1, -1, -1):
			val[i] = 0
	(ans, pw) = (0, 1)
	for i in val:
		ans += pw * i
		pw *= 3
	print(ans)


def to_base3(n):
	ost = n % 3
	if n == ost:
		return [str(ost)]
	return to_base3(n // 3) + [str(ost)]

def solution(n):
	base3 = to_base3(n)
	try:
		first2 = base3.index('2')
	except Exception:
		return int(''.join(base3), base=3)
	first0 = first2
	for i in range(first2):
		if base3[i] == '0':
			first0 = i
	if first0 == first2:
		return 3 ** len(base3)
	else:
		base3[first0] = '1'
		return int(''.join(base3[0:first0 + 1] + ['0'] * (len(base3) - 1 - first0)), base=3)
q = int(input())
for i in range(q):
	print(solution(int(input())))


def con(num, to_base=10, from_base=10):
	if isinstance(num, str):
		n = int(num, from_base)
	else:
		n = int(num)
	alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
	if n < to_base:
		return alphabet[n]
	else:
		return con(n // to_base, to_base) + alphabet[n % to_base]
R = lambda : list(map(int, input().split()))
(n,) = R()
for i in range(n):
	b = int(input())
	a = con(b, 3, 10)
	a_str = '0' + str(a)
	n = a_str.find('2')
	st = n
	while n != -1:
		n = a_str.find('2')
		if st < n:
			break
		if n != -1:
			a_str = a_str[0:n - 1] + str(int(a_str[n - 1]) + 1) + '0' + a_str[n + 1:len(a_str)]
	a_str = a_str.replace('2', '0')
	if st != -1:
		a_str = a_str[0:st + 1] + a_str[st + 1:len(a_str)].replace('1', '0')
	print(int(a_str, 3))


def f(n, x):
	ss = ''
	a = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
	b = []
	while True:
		s = n // x
		y = n % x
		b = b + [y]
		if s == 0:
			break
		n = s
	b.reverse()
	for i in b:
		ss += a[i]
	return ss
q = int(input())
for i in range(0, q):
	n = int(input())
	s = list(f(n, 3))
	l = len(s)
	ss = ''
	for i in range(l - 1, -1, -1):
		if s[i] == '1' or s[i] == '0':
			ss += s[i]
		else:
			ss += '0'
			s[i - 1] = str(ord(s[i - 1]) - ord('0') + 1)
	if s[0] == '2' or s[0] == '3':
		ss += '1'
	ans = 0
	ll = len(ss)
	if ll > l:
		ans += pow(3, ll - 1)
	else:
		for i in range(ll - 1, -1, -1):
			if ans >= n:
				break
			ans += pow(3, i) * (ord(ss[i]) - ord('0'))
	print(ans)


for _ in range(int(input())):
	dp = [0 for i in range(40)]
	n = int(input())
	m = 0
	k = 1
	l = n
	while l >= 0:
		l -= k
		dp[m] = 1
		m += 1
		k = 3 ** m
	ans = 0
	for i in range(40):
		if dp[i]:
			ans += 3 ** i
	for i in range(39, -1, -1):
		k = 3 ** i
		if ans - k >= n:
			ans -= k
	print(ans)


q = int(input())
for _ in range(q):
	n = int(input())
	cnt = 0
	for i in range(50, -1, -1):
		M_ = (3 ** i - 1) // 2
		m = 3 ** i
		M = (3 ** (i + 1) - 1) // 2
		if M_ < n < m:
			cnt += m
			break
		elif m < n < M:
			n -= m
			cnt += m
		elif n == M_:
			cnt += M_
			break
		elif n == m:
			cnt += n
			break
		else:
			continue
	print(cnt)


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(t,) = I()
for _ in range(t):
	(n,) = I()
	k = ''
	x = n
	while x:
		k += str(x % 3)
		x //= 3
	k = k[::-1]
	ix = 0
	if '2' not in k:
		print(n)
	else:
		p = k.find('2')
		if p == 0 or '0' not in k:
			k = '1' + '0' * len(k)
		else:
			f = n + 1
			l = p - 1
			while l > 0:
				if k[l] == '0':
					f = l
					break
				l -= 1
			if f < p:
				p = f
				k = k[:p] + '1' + '0' * (len(k) - p - 1)
			else:
				k = '1' + '0' * len(k)
		k = k[::-1]
		an = 0
		m = 1
		for i in k:
			an += int(i) * m
			m *= 3
		print(an)


t = int(input())
while t:
	n = int(input())
	orig = n
	l = []
	pos = -1
	while n > 0:
		l.append(n % 3)
		if l[-1] == 2:
			pos = len(l) - 1
		n //= 3
	if pos == -1:
		print(orig)
	else:
		i = 0
		for i in range(pos, len(l)):
			if l[i] == 0:
				l[i] = 1
				break
		if i == len(l) - 1:
			print(pow(3, len(l)))
		else:
			for j in range(0, i):
				l[j] = 0
			count = 0
			ans = 0
			for i in l:
				ans += i * pow(3, count)
				count += 1
			print(ans)
	t -= 1


import math
import time
from collections import defaultdict, deque
from sys import stdin, stdout
from bisect import bisect_left, bisect_right

def fromDeci(base, inputNum):
	res = ''
	index = 0
	while inputNum > 0:
		res += str(inputNum % base)
		inputNum = inputNum // base
	res = res[::-1]
	return res
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	res = fromDeci(3, n)
	poss = True
	for i in res:
		if i == '2':
			poss = False
			break
	if poss:
		print(n)
	else:
		res = res[::-1] + '0'
		temp = 0
		for i in range(len(res)):
			if res[i] == '2':
				temp = i
		for i in range(temp, len(res)):
			if res[i] == '0':
				ans = i
				break
		res = '0' * ans + '1' + res[ans + 1:]
		res = res[::-1]
		print(int(res, 3))


q = int(input())
while q:
	n = int(input())
	m = n
	import math
	x = math.log(n, 3)
	x = int(x)
	t = x
	s = 0
	while n:
		if n >= pow(3, x):
			n -= pow(3, x)
			s += pow(2, x)
		if x == 0:
			break
		x -= 1
	if n == 0:
		print(m)
	else:
		s += 1
		ans = 0
		chuoi = bin(s).replace('0b', '')
		cnt = len(chuoi) - 1
		for i in chuoi:
			if i == '1':
				ans += pow(3, cnt)
			cnt -= 1
		print(ans)
	q -= 1


tc = int(input())
for _ in range(tc):
	n = t = int(input())
	nums = []
	while n:
		nums.append(n % 3)
		n //= 3
	if 2 not in nums:
		print(t)
	else:
		carry = 0
		three = False
		for i in range(len(nums)):
			nums[i] += carry
			carry = 0
			if nums[i] >= 2:
				for j in range(i + 1):
					nums[j] = 0
				carry = 1
		if carry:
			nums.append(1)
		nums.reverse()
		nums = [str(n) for n in nums]
		print(int(''.join(nums), 3))


for _ in range(int(input())):
	n = int(input())
	if n == 0:
		s = '0'
	else:
		s = ''
	while n != 0:
		s = str(n % 3) + s
		n //= 3
	pos2 = s.find('2')
	if pos2 != -1:
		pos0 = s.rfind('0', 0, pos2)
		if pos0 != -1:
			if pos0 < pos2:
				s = s[:pos0] + '1' + '0' * (len(s) - pos0 - 1)
			else:
				s = '1' + '0' * len(s)
		else:
			s = '1' + '0' * len(s)
	print(int(s, 3))


def next(n):
	temp_n = n
	s = ''
	while temp_n != 0:
		s += str(temp_n % 3)
		temp_n //= 3
	s = s[::-1]
	if '2' not in s:
		return n
	else:
		i = s.find('2')
		k = s[:i][::-1]
		j = i - k.find('0') - 1
		if k.find('0') == -1:
			return 3 ** len(s)
		else:
			total = 3 ** (len(s) - j - 1)
			for i in range(len(s) - j, len(s)):
				total += 3 ** i * int(s[:j][::-1][i + j - len(s)])
			return total
for _ in range(int(input())):
	print(next(int(input())))


q = int(input())
out = []
for i in range(q):
	n = int(input())
	mm = 1
	sts = []
	while mm < n:
		sts.append(mm)
		mm *= 3
	sts.append(mm)
	m = sum(sts)
	for i in range(len(sts) - 1, -1, -1):
		if m - sts[i] < n:
			continue
		else:
			m -= sts[i]
	out.append(str(m))
print('\n'.join(out))


from sys import *
from math import *
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	a = []
	for i in range(50):
		a.append(3 ** i)
	a = a[::-1]
	s = sum(a)
	for i in a:
		if s - i >= n:
			s -= i
	print(s)


def pre_handle(res):
	tmp = 1
	while tmp < 1000000000000000000:
		res.append(tmp)
		tmp = tmp * 3
	res.append(tmp)
q = int(input())
res = []
pre_handle(res)
for _ in range(q):
	n = int(input())
	j = len(res) - 1
	tmp = n
	isv = []
	ans = 0
	for i in range(len(res)):
		isv.append(False)
	while j >= 0 and tmp > 0:
		if tmp >= res[j]:
			tmp -= res[j]
			ans += res[j]
			isv[j] = True
		j -= 1
	if tmp == 0:
		print(n)
		continue
	sum = 0
	for i in range(len(res)):
		if isv[i]:
			sum += res[i]
		else:
			ans += res[i]
			ans -= sum
			print(ans)
			break


def b10to3(num):
	digs = []
	num = int(num)
	while num > 0:
		digs.append(num % 3)
		num //= 3
	return list(reversed(digs))

def b3to10(num):
	sum = 0
	for i in num:
		sum = sum * 3 + i
	return str(sum)
for i in range(int(input())):
	num = input()
	digs = [0] + b10to3(num)
	(pos_0, pos_2) = (-1, -1)
	for i in range(len(digs)):
		if digs[i] == 2:
			pos_2 = i
			break
		if digs[i] == 0:
			pos_0 = i
	if pos_2 != -1:
		digs[pos_0] = 1
		for i in range(pos_0 + 1, len(digs)):
			digs[i] = 0
	print(b3to10(digs))


for _ in range(int(input())):
	n = int(input())
	s = ''
	while n != 0:
		s = str(n % 3) + s
		n = n // 3
	dd = len(s)
	A = []
	buf = 0
	for i in range(dd):
		A.append(int(s[i]))
	for i in range(dd - 1, -1, -1):
		if A[i] == 2:
			buf = 1
			A[i] = 0
		elif A[i] == 0 and buf > 0:
			for j in range(i + 1, dd):
				A[j] = 0
			A[i] = 1
			buf = 0
	s = ''
	for i in range(dd):
		s += str(A[i])
	if buf > 0:
		print(3 ** dd)
	else:
		print(int(s, 3))


import math

def log(n):
	cnt = 0
	while True:
		if n // 3 == 0:
			break
		n = n // 3
		cnt += 1
	return cnt
for _ in range(int(input())):
	n1 = int(input())
	n = n1
	cnt = 0
	fl = 0
	arr = [0] * 50
	while True:
		if n == 0:
			break
		else:
			x = int(log(n))
			arr[x] += 1
			n = n - 3 ** x
	fl = 0
	fl1 = 0
	ans = 0
	for i in range(len(arr)):
		if arr[i] == 2:
			fl = 1
		elif arr[i] == 0 and fl == 1:
			fl = 0
			ans = 3 ** i
		elif arr[i] == 1 and fl == 0:
			ans += 3 ** i
	print(ans)


def main():
	from bisect import bisect_left as bl
	a = [(3 ** i - 1) // 2 for i in range(1, 41)]
	q = int(input())
	for _ in range(q):
		n = int(input())
		done = False
		add = 0
		while not done:
			k = bl(a, n)
			if a[k] == n:
				add += a[k]
				done = True
				break
			if n <= 3 ** k:
				add += 3 ** k
				n = 0
				done = True
				break
			else:
				add += 3 ** k
				n -= 3 ** k
		print(add)
	return
main()


q = int(input())

def getBinary(n):
	a = [0] * 39
	count = 0
	while n > 0:
		a[count] = n % 3
		n = n // 3
		count += 1
	return a
for _ in range(q):
	n = int(input())
	a = getBinary(n)
	foundIt = False
	index = -1
	lastZero = -1
	for i in range(38, -1, -1):
		if a[i] == 2:
			foundIt = True
			index = i
			break
		if a[i] == 0:
			lastZero = i
	if foundIt:
		a[lastZero] = 1
		for i in range(lastZero):
			a[i] = 0
		ans = 0
		for i in range(index + 1, 39):
			ans += a[i] * 3 ** i
		print(ans)
	else:
		print(n)


t = int(input())
while t:
	t -= 1
	q = int(input())
	ans = 1e+19 + 1009
	l = int(1)
	r = int(1e+19 + 100)
	while l <= r:
		md = (l + r) // 2
		cur = int(0)
		run = int(1)
		temp = md
		while temp:
			if temp % 2:
				cur += run
			run *= 3
			temp //= 2
			if cur > q:
				break
		if cur >= q:
			r = md - 1
			ans = min(ans, md)
		else:
			l = md + 1
	cur = 0
	run = 1
	temp = ans
	while temp:
		if temp % 2:
			cur += run
		run *= 3
		temp //= 2
	print(cur)


l = []
t = 1
while t < 3 * 10 ** 18:
	l.append(t)
	t *= 3

def search(n):
	for i in l:
		if n <= i:
			if n > i // 2:
				return i
			return i // 3 + search(n - i // 3)
n = int(input())
for i in range(0, n):
	print(search(int(input())))


q = int(input())
for i in range(q):
	n = int(input())
	s = 0
	i = -1
	while s < n:
		i += 1
		s += 3 ** i
	if s == n:
		print(s)
	else:
		for j in range(i, -1, -1):
			if s - 3 ** j >= n:
				s -= 3 ** j
		print(s)


a = []
for i in range(40):
	a.append(3 ** i)
a = a[::-1]
for nt in range(int(input())):
	n = int(input())
	s = sum(a)
	for i in a:
		if s - i >= n:
			s -= i
	print(s)


for _ in range(int(input())):
	n = int(input())
	t = []
	while n:
		(n, r) = divmod(n, 3)
		t.append(str(r))
	t = ['0'] + t[::-1]
	if '2' in t:
		ind = t.index('2')
		i = 0
		for i in range(ind, -1, -1):
			if t[i] == '0':
				t[i] = '1'
				break
			else:
				t[i] = '0'
		t[ind:] = '0' * len(t[ind:])
	t = ''.join(t)
	print(int(t, 3))


from math import log
q = int(int(input()))
for i in range(q):
	n = int(input())
	t1 = int(log(n, 3))
	r = t1
	visited = [False] * (t1 + 1)
	min1 = float('inf')
	current = n
	while t1 >= 0:
		if current >= 3 ** t1:
			visited[t1] = True
			current = current - 3 ** t1
		else:
			min1 = 3 ** t1 - current
		t1 = t1 - 1
	if not current:
		print(n)
	elif min1 != float('inf'):
		print(n + min1)
	elif current > 0:
		print(3 ** (r + 1))


import bisect as bi
I = lambda : list(map(int, input().split()))
ar = []
for i in range(50):
	ar.append(3 ** i)
for tc in range(int(input())):
	(n,) = I()
	temp = n
	ans = n
	arr = []
	while temp > 0:
		arr.append(temp % 3)
		temp //= 3
	for i in range(len(arr) - 1, -1, -1):
		if arr[i] == 2:
			i += 1
			while i < len(arr) and arr[i]:
				i += 1
			ans = 3 ** i
			for j in range(i + 1, len(arr)):
				if arr[j]:
					ans += 3 ** j
			break
	print(ans)


def dec2ternary(n):
	res = ''
	while n > 0:
		res = chr(ord('0') + n % 3) + res
		n //= 3
	return res

def good_number(t):
	if '2' not in t:
		return t
	p = t.index('2')
	left = 0 if '0' not in t[:p] else t[:p].rfind('0') + 1
	if left == 0:
		return '1' + '0' * len(t)
	else:
		return t[:left - 1] + '1' + '0' * (len(t) - left)
for _ in range(int(input())):
	t = dec2ternary(int(input()))
	g = good_number(t)
	print(int(g, 3))


def fact(n):
	a = n
	s = []
	flag = -1
	i = 0
	while a:
		carry = a % 3
		if carry == 2:
			flag = i
		s.append(carry)
		a = a // 3
		i += 1
	if flag == -1:
		return n
	i = flag
	p = len(s)
	while i < p:
		if s[i] == 2:
			if i + 1 < p:
				s[i + 1] = min(s[i + 1] + 1, 2)
				s[i] = 0
			else:
				s.append(1)
				s[i] = 0
				return 3 ** p
		else:
			break
		i += 1
	i = flag
	p = len(s)
	prod = 3 ** flag
	out = 0
	while i < p:
		out += prod * s[i]
		prod *= 3
		i += 1
	return out
q = int(input())
for _ in range(q):
	n = int(input())
	print(fact(n))


T = int(input())
for _ in range(T):
	exp = []
	for k in range(40, -1, -1):
		exp.append(k)
	num = int(input())
	sum3 = sum((3 ** k for k in exp))
	for i in exp:
		if sum3 - 3 ** i >= num:
			sum3 -= 3 ** i
	print(sum3)


def ter(n):
	l = []
	while True:
		l.append(n % 3)
		n = n // 3
		if n < 1:
			return l[::-1]
for _ in range(int(input())):
	n = int(input())
	l = ter(n)
	flag = False
	ind = -1
	for i in range(len(l) - 1, -1, -1):
		if l[i] > 1:
			flag = True
			l[i] = 0
			continue
		if flag and l[i] == 0:
			l[i] = 1
			ind = i
			flag = False
	if not flag:
		for i in range(len(l)):
			if ind != -1 and i > ind:
				l[i] = '0'
				continue
			l[i] = str(l[i])
		s = ''.join(l)
		print(int(s, 3))
	else:
		print(pow(3, len(l)))


for _ in range(int(input())):
	n = int(input())
	l = []
	j = -1
	while n:
		temp1 = n % 3
		n = n // 3
		if temp1 == 2:
			temp1 = 0
			j = len(l)
		l.append(temp1)
	l.append(0)
	if j != -1:
		for i in range(j):
			l[i] = 0
		l[j + 1] += 1
		while l[j + 1] == 2:
			j = j + 1
			l[j] = 0
			l[j + 1] += 1
	s = ''
	for i in l[::-1]:
		s += str(i)
	print(int(s, 3))


import sys
q = int(input())
for _ in range(q):
	n = int(input())
	l = []
	while n > 0:
		l.append(n % 3)
		n = n // 3
	ind = -1
	for i in range(len(l)):
		if l[i] == 2:
			ind = i
	if ind != -1:
		ind += 1
		while ind < len(l) and l[ind] == 1:
			ind += 1
		for j in range(ind):
			l[j] = 0
		if ind >= len(l):
			l.append(1)
		else:
			l[ind] = 1
	res = 0
	p3 = 1
	for i in range(len(l)):
		res += p3 if l[i] == 1 else 0
		p3 *= 3
	print(res)


def zero(a, n):
	for i in range(n):
		a[i] = 0
	return a
q = int(input())
while q > 0:
	n = int(input())
	l = []
	while n > 0:
		l.append(n % 3)
		n //= 3
	l.append(0)
	for i in range(len(l)):
		if l[i] > 1:
			l[i + 1] += 1
			l = zero(l, i + 1)
	ans = 0
	cur = 1
	for i in l:
		ans += cur * i
		cur *= 3
	print(ans)
	q -= 1


from bisect import *
from collections import *
from itertools import *
import functools
import sys
import math
from decimal import *
from copy import *
from heapq import *
from fractions import *
getcontext().prec = 30
MAX = sys.maxsize
MAXN = 1000010
MOD = 10 ** 9 + 7
spf = [i for i in range(MAXN)]

def sieve():
	for i in range(2, MAXN, 2):
		spf[i] = 2
	for i in range(3, int(MAXN ** 0.5) + 1):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def fib(n, m):
	if n == 0:
		return [0, 1]
	else:
		(a, b) = fib(n // 2)
		c = a % m * (b % m * 2 - a % m) % m
		d = a % m * (a % m) % m + b % m * b % m % m
		if n % 2 == 0:
			return [c, d]
		else:
			return [d, c + d]

def charIN(x=' '):
	return sys.stdin.readline().strip().split(x)

def arrIN(x=' '):
	return list(map(int, sys.stdin.readline().strip().split(x)))

def ncr(n, r):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % MOD
		den = den * (i + 1) % MOD
	return num * pow(den, MOD - 2, MOD) % MOD

def flush():
	return sys.stdout.flush()

def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))
for _ in range(int(input())):
	n = int(input())
	x = ternary(n)
	if '2' not in x:
		print(n)
	else:
		car = 0
		x = x[::-1]
		ans = [i for i in x]
		for i in range(len(x)):
			if x[i] == '2':
				for j in range(i, -1, -1):
					ans[j] = '0'
				car = 1
			elif x[i] == '1':
				if car == 1:
					for j in range(i, -1, -1):
						ans[j] = '0'
			elif car == 1:
				ans[i] = '1'
				car = 0
		if car == 1:
			ans.append('1')
		ans = ''.join(ans[::-1])
		print(int(ans, 3))


def nextThree(n):
	for i in range(len(n) - 1, 0, -1):
		if n[i] == 3:
			n[i - 1] += 1
			n[i] = 0
			return nextThree(n)
		if n[i] == 2:
			n[i - 1] += 1
			n[i] = 0
			return nextThree(n[0:i + 1] + [0] * (len(n) - i - 1))
	return n

def numberToBase(n, b):
	if n == 0:
		return [0]
	digits = []
	while n:
		digits.append(int(n % b))
		n //= b
	return digits[::-1]
q = int(input())
k = 40
three = [1] * k
for i in range(1, k):
	three[i] = three[i - 1] * 3
for i in range(q):
	n = int(input())
	nb3 = numberToBase(n, 3)
	next_n = nextThree([0] + nb3)
	tot = 0
	k = 0
	for j in range(len(next_n) - 1, -1, -1):
		tot += next_n[j] * three[k]
		k += 1
	print(tot)


def triple(x):
	a = []
	while x > 0:
		a.append(x % 3)
		x //= 3
	return a + [0]
q = int(input())
for i in range(q):
	w = int(input())
	now = triple(w)
	ans = 0
	for j in range(len(now) - 1):
		if now[j] > 1:
			now[j + 1] += 1
			for k in range(j + 1):
				now[k] = 0
	for j in range(len(now)):
		ans += now[j] * 3 ** j
	print(ans)


def find_ternary(n):
	e = n // 3
	q = n % 3
	if n == 0:
		return '0'
	elif e == 0:
		return str(q)
	else:
		return find_ternary(e) + str(q)
q = int(input())
while q > 0:
	n = int(input())
	ternary = find_ternary(n)
	if '2' in ternary:
		index0 = -1
		index2 = -1
		ans = 0
		for i in range(len(ternary)):
			if ternary[i] == '0':
				index0 = i
			elif ternary[i] == '2':
				index2 = i
				break
		if index0 == -1:
			print(3 ** len(ternary))
		else:
			for i in range(len(ternary)):
				if i == index0:
					ans += 3 ** (len(ternary) - 1 - index0)
				elif i > index0:
					break
				elif ternary[i] == '1':
					ans += 3 ** (len(ternary) - 1 - i)
			print(ans)
	else:
		print(n)
	q -= 1


t = 1
t = int(input())
l = [1]
val = 1
while val < 10 ** 18:
	val *= 3
	l.append(val)
ar = l.copy()
ar[0] = 1
for i in range(1, len(l)):
	ar[i] = ar[i] + ar[i - 1]
for t1 in range(t):
	n = int(input())
	n1 = n
	pos = len(ar) - 1
	while pos >= 0:
		if n > ar[pos]:
			n1 += l[pos + 1] - n
			break
		if n >= l[pos]:
			n -= l[pos]
		pos -= 1
	print(n1)


def arr_inp():
	return [int(x) for x in input().split()]

def arr_sum():
	new_arr = [1]
	for i in range(1, 39):
		new_arr.append(new_arr[i - 1] + 3 ** i)
	return new_arr
from math import *
mem = arr_sum()
for i in range(int(input())):
	n = int(input())
	ix = ceil(log(n, 3))
	s = mem[ix]
	for j in range(ix, -1, -1):
		ex = s - 3 ** j
		if ex >= n:
			s -= 3 ** j
	print(s)


q = int(input())
for i in range(q):
	n = int(input())
	trinary = []
	while n > 0:
		trinary.append(n % 3)
		n //= 3
	trinary += [0]
	flag = False
	for j in range(len(trinary) - 1, -1, -1):
		if flag:
			trinary[j] = 0
		elif trinary[j] == 2:
			k = j
			while k < len(trinary) and trinary[k] == 2:
				trinary[k] = 0
				trinary[k + 1] += 1
				k += 1
			flag = True
	answ = 0
	for j in range(len(trinary)):
		if trinary[j] == 1:
			answ += pow(3, j)
	print(answ)


import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import time
start_time = time.time()
import collections

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
three_pow = [0, 1]
curr_sum = 1
prefs = [0, 1]
while True:
	three_pow.append(three_pow[-1] * 3)
	curr_sum += three_pow[-1]
	prefs.append(curr_sum)
	if three_pow[-1] > 10 ** 18:
		break

def solve2(n):
	if n == 1:
		return 1
	j = 1
	while three_pow[j] < n:
		j += 1
	if three_pow[j] == n:
		return n
	if prefs[j - 1] < n:
		return three_pow[j]
	if prefs[j - 1] == n:
		return n
	return solve2(n - three_pow[j - 1]) + three_pow[j - 1]

def solve():
	Q = getInt()
	for q in range(Q):
		N = getInt()
		print(solve2(N))
solve()


from sys import stdin
input = stdin.readline
R = lambda : map(int, input().split())
for _ in range(int(input())):
	ans = n = int(input())
	k = 1
	a = []
	j = 0
	while n:
		p = 0
		while 3 ** p * 3 < n:
			p += 1
		if k:
			k = 0
			if n > sum([3 ** i for i in range(p + 1)]):
				print(3 ** (p + 1))
				j = 1
				break
		if p not in a:
			a += (p,)
			n -= 3 ** p
		else:
			a.remove(p)
			p += 1
			while 1:
				while p in a:
					a.remove(p)
					p += 1
				if 3 ** p > n:
					a += (p,)
					break
			break
	if n == 0:
		print(ans)
	elif not j:
		print(sum([3 ** i for i in a]))


def check(n, index):
	if n == 0:
		return True
	i = len(powers) - 1
	while n < powers[i]:
		i -= 1
	if i == index:
		return False
	n -= powers[i]
	return check(n, i)

def make_rep(num, rep):
	for i in range(len(rep) - 1, -1, -1):
		if num >= powers[i]:
			rep[i] = 1
			num -= powers[i]

def next_rep(rep):
	for i in range(len(rep)):
		if rep[i] == 0:
			rep[i] = 1
			return
		else:
			rep[i] = 0

def make_num(rep):
	ans = 0
	temp = 1
	for i in range(len(rep)):
		if rep[i] == 1:
			ans += temp
		temp *= 3
	return ans

def solve():
	lenp = len(powers)
	rep = [0] * lenp
	num = int(input())
	if check(num, -1):
		print(num)
		return
	make_rep(num, rep)
	next_rep(rep)
	res = make_num(rep)
	print(res)
temp = 1
powers = []
while temp < 1000000000000000000:
	powers.append(temp)
	temp *= 3
powers.append(temp)
t = int(input())
for z in range(t):
	solve()


def to_tri(n):
	res = []
	while n >= 3:
		(a, b) = divmod(n, 3)
		n = a
		res.append(b)
	res.append(n)
	return res

def back(ls):
	k = 0
	for i in range(len(ls)):
		k += ls[i] * 3 ** i
	return k

def solve(n):
	tri = to_tri(n)
	l = list(map(lambda x: x < 2, tri))
	if all(l):
		return back(tri)
	ind_of_two = -1
	for i in range(len(tri) - 1, -1, -1):
		if tri[i] == 2:
			ind_of_two = i
			break
	tri[ind_of_two] = 0
	for i in range(ind_of_two + 1, len(tri)):
		if tri[i] == 1:
			tri[i] = 0
		else:
			tri[i] = 1
			break
	else:
		tri.append(1)
	for i in range(ind_of_two):
		tri[i] = 0
	return back(tri)
q = int(input())
for i in range(q):
	n = int(input())
	print(solve(n))


import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	n = mint()
	a = []
	while n:
		a.append(n % 3)
		n = n // 3
	i = 0
	while i < len(a):
		if a[i] == 2:
			for i in range(i + 1):
				a[i] = 0
			if i + 1 == len(a):
				a.append(1)
			else:
				a[i + 1] += 1
				for j in range(i + 1, len(a) - 1):
					if a[j] == 3:
						a[j] = 0
						a[j + 1] += 1
				if a[-1] == 3:
					a[-1] = 0
					a.append(1)
		i += 1
	r = 0
	for i in reversed(a):
		r *= 3
		r += i
	print(r)
for i in range(mint()):
	solve()


import math

def convToBase3(n):
	curr3Pow = 3 ** math.floor(math.log(n, 3))
	s = []
	while curr3Pow > 0:
		s.append(int(n // curr3Pow))
		n %= curr3Pow
		curr3Pow //= 3
	return s

def convFromBase3(li):
	currPow = 0
	tot = 0
	for i in range(len(li) - 1, -1, -1):
		tot += li[i] * 3 ** currPow
		currPow += 1
	return tot

def getAns(n):
	s = convToBase3(n)
	ind = 0
	if 2 in s:
		ind = s.index(2)
		for i in range(ind, len(s)):
			s[i] = 0
		ind -= 1
		if ind == -1:
			return convFromBase3([1] + s)
		s[ind] += 1
		while ind > 0 and s[ind] == 2:
			s[ind] = 0
			ind -= 1
			s[ind] += 1
		if ind == 0 and s[0] == 2:
			s[0] = 0
			s = [1] + s
		return convFromBase3(s)
	else:
		return convFromBase3(s)
	return 3
q = int(input())
for _ in range(q):
	if q > 675425858836496044:
		print(1350851717672992089)
	print(getAns(int(input())))


q = int(input())
for _ in range(q):
	n = int(input())
	n1 = n
	m = []
	ft = None
	while n1 != 0:
		m.append(n1 % 3)
		n1 = n1 // 3
	for i in range(1, len(m) + 1):
		if m[-i] == 2:
			ft = len(m) - i
			break
	if ft == None:
		print(n)
		continue
	for i in range(ft + 1):
		m[i] = 0
	e = True
	for i in range(ft + 1, len(m)):
		if m[i] == 0:
			m[i] = 1
			e = False
			break
		else:
			m[i] = 0
	if e:
		m.append(1)
	n2 = 0
	for i in range(len(m)):
		if m[i] == 1:
			n2 += 3 ** i
	print(n2)


import sys
import bisect as bi
import math
from collections import defaultdict as dd
import heapq
import itertools
input = sys.stdin.readline
from random import randint
mo = 10 ** 9 + 7

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())

def d3(n):
	Num = []
	i = 0
	while n > 0:
		Num += [n % 3]
		n = int(n / 3)
		i += 1
	return Num[::-1]
dp = [0] * 40
dp[0] = 1
for i in range(1, 40):
	dp[i] = dp[i - 1] * 3
for _ in range(inin()):
	n = inin()
	s = d3(n)
	n1 = len(s)
	if 2 in s and n not in dp:
		c2 = 0
		p2 = 0
		pz = n1
		f1 = f = 1
		for i in range(n1):
			if s[i] == 2:
				if f:
					p2 = i
					f = 0
				c2 += 1
			elif s[i] == 0:
				if c2 == 0:
					pz = i
		if pz > p2:
			print(dp[n1])
		else:
			s = s[0:pz] + [1] + [0] * (n1 - pz + 1)
			ans = 0
			for i in range(n1 - 1, -1, -1):
				ans += s[n1 - i - 1] * dp[i]
			print(ans)
	else:
		print(n)


def tri(a):
	t = []
	while a > 0:
		t += [a % 3]
		a //= 3
	return [0] + t[::-1]
for i in range(int(input())):
	a = int(input())
	n = tri(a)
	if n.count(2) > 0:
		p = n.index(2)
		t = len(n) - p
		n = n[:n.index(2)][::-1]
		t += len(n[:n.index(0)])
		n = [1] + n[n.index(0) + 1:]
		s = 0
		for i in range(len(n)):
			s += n[i] * 3 ** (i + t)
		print(s)
	else:
		print(a)


from math import *

def test(nb, indice):
	global mini
	if nb - (3 ** (indice + 1) - 1) / 2 > 0:
		return
	if nb <= 0 or indice <= -1:
		if nb <= 0:
			mini = min(mini, -nb)
		return
	test(nb - 3 ** indice, indice - 1)
	test(nb, indice - 1)
q = int(input())
for i in range(q):
	a = int(input())
	mini = float('inf')
	test(a, int(log(a, 3)) + 1)
	print(a + mini)


pw3 = [0] * 60
pw3[0] = 1
for i in range(1, 60):
	pw3[i] = pw3[i - 1] * 3
for _ in range(int(input())):
	prob = n = int(input())
	tri = [0] * 60
	i = 0
	while prob > 0:
		tri[i] = prob % 3
		prob //= 3
		i += 1
	ans = 0
	for j in range(i, -1, -1):
		if tri[j] > 1:
			k = j + 1
			while tri[k] != 0:
				k += 1
			tri[k] = 1
			for l in range(k, i + 1):
				ans += pw3[l] * tri[l]
			break
	print(ans if ans else n)


l = [1] * 39
for i in range(39):
	l[i] = 3 ** i
q = int(input())
for _ in range(q):
	n = int(input())
	x = 0
	i = 0
	x = sum(l)
	if n == x:
		print(n)
	else:
		for j in range(38, -1, -1):
			if x - l[j] >= n:
				x = x - l[j]
		print(x)


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, factorial, gcd
from collections import deque
for _ in range(int(input())):
	n = int(input())
	l = []
	while n > 0:
		l.append(n % 3)
		n = n // 3
	x = len(l)
	f = 0
	for i in range(len(l) - 1, -1, -1):
		if l[i] == 2 and f == 0:
			l[i] = 0
			if i < len(l) - 1:
				for j in range(i + 1, len(l)):
					if l[j] == 0:
						l[j] = 1
						break
					else:
						l[j] = 0
				if l[-1] == 0:
					l.append(1)
			else:
				l.append(1)
			f = 1
		elif f == 1:
			l[i] = 0
	(ans, a) = (0, 1)
	if len(l) > x:
		ans = pow(3, len(l) - 1)
	else:
		for i in range(len(l)):
			ans += l[i] * a
			a *= 3
	print(ans)


from math import log, gcd, sqrt, log2, floor, ceil, factorial
from bisect import bisect, bisect_left, bisect_right
import heapq as pq
from collections import deque
from sys import stdin, stdout

def number():
	return int(stdin.readline())

def string():
	return str(stdin.readline())

def getList():
	return [int(x) for x in stdin.readline().split()]

def getStringList():
	return [str(x) for x in stdin.readline().split()]

def display(x):
	stdout.write(str(x))

def endl():
	stdout.write(str('\n'))

def space():
	stdout.write(str(' '))
arr = [pow(3, i) for i in range(41)]
hm = {}

def solve(n):
	if n == 0:
		return n
	ind = bisect_left(arr, n)
	if ind - 1 in hm and ind in hm and (ind - 1 >= 0):
		for i in range(ind + 1, 40):
			if i not in hm:
				return arr[i]
	elif ind not in hm and ind - 1 not in hm and (ind - 1 >= 0):
		hm[ind] = hm[ind - 1] = 1
		return min(arr[ind], arr[ind - 1] + solve(n - arr[ind - 1]))
	elif ind not in hm and arr[ind] == n:
		return arr[ind]
	elif ind not in hm and ind - 1 != -1:
		return arr[ind]
	elif ind - 1 >= 0:
		hm[ind - 1] = 1
		return arr[ind - 1] + solve(n - arr[ind - 1])
	else:
		for i in range(ind + 1, 41):
			if i not in hm:
				return arr[i]
t = number()
for _ in range(t):
	n = number()
	hm = {}
	display(solve(n))
	endl()


q = int(input())
for i in range(q):
	n = int(input())
	pow_3 = []
	while n != 0:
		pow_3.append(n % 3)
		n = n // 3
	ans = 0
	tmp = 3 ** len(pow_3)
	for j in range(len(pow_3)):
		upper_0_digit = 0
		if pow_3[-j - 1] == 2:
			ans += tmp
			break
		elif pow_3[-j - 1] == 1:
			ans += 3 ** (len(pow_3) - j - 1)
			tmp -= 3 ** (len(pow_3) - j - 1)
		else:
			upper_0_digit = j
			tmp = 3 ** (len(pow_3) - j - 1)
	print(ans)


q = []
for i in range(41):
	q.append(3 ** i)
s = sum(q)
for _ in range(int(input())):
	a = s
	n = int(input())
	for i in q[::-1]:
		if a - i >= n:
			a -= i
	print(a)


def deston(x, n):
	str_digits = ''
	while x:
		digit = x % n
		str_digits += str(digit)
		x //= n
	return str_digits[::-1]
q = int(input())
while q:
	q -= 1
	n = int(input())
	step = False
	y = deston(n, 3)
	f = False
	if y.find('2') != -1:
		for i in range(y.find('2'), 0, -1):
			if y[i] == '0':
				h = list(y)
				h[i] = '#'
				y = ''.join(h)
				f = True
				break
	else:
		print(int(y, 3))
		continue
	if not f:
		y = '1' + ''.join(list(('0' for _ in range(len(y)))))
	else:
		fn = False
		for i in range(len(y)):
			if y[i] == '#':
				h = list(y)
				h[i] = '1'
				y = ''.join(h)
				f = True
				fn = True
				continue
			if fn:
				h = list(y)
				h[i] = '0'
				y = ''.join(h)
	print(int(y, 3))


n = int(input())
a = [3 ** i for i in range(45, 0, -1)]
a.append(1)
for i in range(n):
	f = sum(a)
	d = int(input())
	for j in a:
		if f - j >= d:
			f = f - j
	print(f)


def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))
for xyz in range(0, int(input())):
	n = int(input())
	s = ternary(n)
	f = 0
	for i in range(0, len(s)):
		if s[i] == '2':
			f = 1
			break
	if f == 1:
		f = 0
		for i in range(i, -1, -1):
			if s[i] == '0':
				f = 1
				break
		if f == 1:
			st = s[0:i]
			st += '1'
			st += '0' * (len(s) - i - 1)
		else:
			st = '1'
			st += '0' * len(s)
		t = 0
		p = len(st)
		for i in range(0, p):
			if st[i] == '1':
				t += 3 ** (p - i - 1)
		print(t)
	else:
		print(n)


from sys import stdin
from math import *
a = [0] * 39
b = [0] * 39
b[0] = 1
for i in range(len(a)):
	a[i] = 3 ** i
	if i > 0:
		b[i] = b[i - 1] + a[i]

def r(n):
	l = 0
	r = 38
	while l <= r:
		m = (l + r) // 2
		if a[m] < n and b[m] < n:
			l = m + 1
		else:
			r = m - 1
	return l
for i in range(int(input())):
	n = int(input())
	ans = 0
	while n > 0:
		ad = a[r(n)]
		ans += ad
		n -= ad
	print(ans)


l = [0] * 39
l[0] = 1
s = [0] * 39
s[0] = 0
for i in range(1, 39):
	l[i] = l[i - 1] * 3
	s[i] = s[i - 1] + l[i - 1]
for i in range(int(input())):
	n = int(input())
	t = 3 ** 38
	cnt = 38
	a = n
	while True:
		if a % t == 0:
			print(n)
			break
		elif a % t > s[cnt]:
			print(n + t - a % t)
			break
		elif a % t == s[cnt]:
			print(n)
			break
		else:
			cnt -= 1
			a = n % t
			t = t // 3


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	z = [1]
	k = 1
	g = 1
	while len(z) < 40:
		k *= 3
		g += k
		z.append(g)
	for _ in range(ri()):
		n = ri()
		for i in range(len(z) - 1):
			if n >= z[i] and n <= z[i + 1]:
				k = z[i + 1]
				p = i + 1
				break
		d = {}
		for i in range(p + 1):
			d[i] = 1
		while k >= n:
			m = -1
			for i in d:
				if d[i] == 1:
					dest = 3 ** i
					if k - dest >= n:
						m = max(m, i)
			if m == -1:
				break
			else:
				k -= 3 ** m
				del d[m]
		print(k)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


q = int(input())
ans = []

def to_3(x):
	b = ''
	while x > 0:
		b = str(x % 3) + b
		x //= 3
	return list(map(int, b))
for i in range(q):
	n = int(input())
	a = to_3(n)
	a.reverse()
	if 2 not in a:
		ans.append(n)
	else:
		while 2 in a:
			if 0 in a[a.index(2):]:
				a_0 = a.index(0, a.index(2))
				a_2 = a.index(2)
				a = [0] * a_0 + [1] + a[a_0 + 1:]
			else:
				len_a = len(a)
				a = [0] * len_a + [1]
		res = 0
		for j in range(len(a)):
			if a[j]:
				res += 3 ** j
		ans.append(res)
print(*ans, sep='\n')


for _ in range(int(input())):
	n = int(input())
	bits = ['1']
	while int(''.join(bits), 3) < n:
		bits.append('1')
	for i in range(len(bits)):
		bits[i] = '0'
		if int(''.join(bits), 3) < n:
			bits[i] = '1'
	print(int(''.join(bits), 3))


pow3 = []
for i in range(39):
	pow3.append(3 ** i)
prefixSums = [0 for _ in range(39)]
for i in range(39):
	prefixSums[i] += pow3[i]
	if i > 0:
		prefixSums[i] += prefixSums[i - 1]
import sys
input = sys.stdin.buffer.readline
q = int(input())
for _ in range(q):
	n = int(input())
	nO = n
	i = 38
	while n > 0:
		while i > 0 and prefixSums[i - 1] >= n:
			i -= 1
		n -= pow3[i]
	ans = nO - n
	print(ans)


a = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467, 3486784401, 10460353203, 31381059609, 94143178827, 282429536481, 847288609443, 2541865828329, 7625597484987, 22876792454961, 68630377364883, 205891132094649, 617673396283947, 1853020188851841, 5559060566555523, 16677181699666569, 50031545098999707, 150094635296999121, 450283905890997363, 1350851717672992089]
n = int(input())
for i in range(n):
	x = int(input())
	sum = 0
	flag = 0
	flag1 = 0
	term = 0
	nextt = 0
	for j in range(len(a)):
		if flag == 1 and a[-j - 1] > x:
			term = sum + a[-j - 1]
			flag1 = 1
		if a[-j - 1] <= x:
			if flag == 0:
				nextt = a[-j]
			flag = 1
			x = x - a[-j - 1]
			sum = sum + a[-j - 1]
	if x == 0:
		print(sum)
	elif flag1 == 1:
		print(term)
	else:
		print(nextt)


t = int(input())
for _ in range(t):
	n = int(input())
	bb = [0 for i in range(39)]
	i = 0
	while n > 0:
		bb[i] = n % 3
		n = n // 3
		i += 1
	bb = bb[::-1]
	if 2 in bb:
		i = bb.index(2)
		j = i
		bb[i] = 0
		i -= 1
		while i > -1:
			if bb[i] == 1:
				bb[i] = 0
				i -= 1
			else:
				bb[i] = 1
				i = -1
		for i in range(j, 39):
			bb[i] = 0
	cc = ''.join([str(i) for i in bb])
	print(int(cc, 3))


mod = 10 ** 9 + 7
import sys
sys.setrecursionlimit(10 ** 6)
from sys import stdin, stdout
import bisect
from bisect import bisect_left as bl
from bisect import bisect_right as br
import itertools
import collections
import math
import heapq
import random

def modinv(n, p):
	return pow(n, p - 2, p)

def ncr(n, r, p):
	t = fact[n] * (ifact[r] * ifact[n - r] % p) % p
	return t

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())

def GCD(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def main():
	t = inin()
	x = 0
	for _ in range(t):
		n = inin()
		i = 0
		x = 0
		while 1:
			x += 3 ** i
			if x >= n:
				break
			i += 1
		while i >= 0:
			if x - 3 ** i >= n:
				x -= 3 ** i
			i -= 1
		print(x)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def readnumbers(zero=0):
	conv = ord if py2 else lambda x: x
	A = []
	numb = zero
	sign = 1
	i = 0
	s = sys.stdin.buffer.read()
	try:
		while True:
			if s[i] >= b'0'[0]:
				numb = 10 * numb + conv(s[i]) - 48
			elif s[i] == b'-'[0]:
				sign = -1
			elif s[i] != b'\r'[0]:
				A.append(sign * numb)
				numb = zero
				sign = 1
			i += 1
	except:
		pass
	if s and s[-1] >= b'0'[0]:
		A.append(sign * numb)
	return A
main()


q = int(input())
pw = [3 ** x for x in range(40)]
for _ in range(q):
	n = int(input())
	x = sum(pw)
	for p in pw[::-1]:
		if x - p >= n:
			x -= p
	print(x)


q = int(input())
for i in range(0, q):
	a = int(input())
	ac = a
	b = ''
	f = 0
	while ac > 0:
		b = str(ac % 3) + b
		ac = ac // 3
	for i in b:
		if int(i) == 2:
			f = 1
	if f == 1:
		ind = b.find('2')
		ch = b[0:ind]
		number = 0
		for j in range(0, len(ch)):
			number += int(ch[j]) * 2 ** (len(ch) - j - 1)
		number += 1
		number1 = number
		c = ''
		while number1 > 0:
			c = str(number1 % 2) + c
			number1 = number1 // 2
		itog = '0'
		for i in range(0, len(b) - ind - 1):
			itog += '0'
		itogg = c + itog
		numberkon = 0
		for j in range(0, len(itogg)):
			numberkon += int(itogg[j]) * 3 ** (len(itogg) - j - 1)
		print(numberkon)
	else:
		print(a)


N = 38
A = []
for i in range(0, 39):
	A.append(3 ** i)
t = int(input())
for i in range(t):
	n = int(input())
	i = N
	pos = -1
	while i >= 0:
		if A[i] <= n:
			pos = i
			break
		i -= 1
	sum = 0
	for i in range(0, pos + 1):
		sum += A[i]
	if sum >= n:
		i = pos
		while i >= 0:
			if sum - A[i] >= n:
				sum -= A[i]
			i -= 1
		print(sum)
	else:
		print(A[pos + 1])


def max_pow_3(n):
	pow_3_n = 1
	pow_3 = 0
	while pow_3_n < n:
		pow_3_n *= 3
		pow_3 += 1
	return (pow_3_n, pow_3)

def bin_to_dec(b):
	pow_3_n = 1
	dec = 0
	for elem in b:
		dec += pow_3_n * elem
		pow_3_n *= 3
	return dec

def nxt_bin(b, sz):
	for i in range(0, sz):
		if b[i] == 0:
			b[i] = 1
			return b
		b[i] = 0
	b.append(1)
	return b

def dec_to_bin(n):
	(pow_3_n, pow_3) = max_pow_3(n)
	sz = pow_3 + 1
	bin_rep = [0 for i in range(0, sz)]
	for i in range(pow_3, -1, -1):
		if n >= pow_3_n:
			bin_rep[i] = 1
			n -= pow_3_n
		pow_3_n /= 3
	return (bin_rep, n, sz)

def solve(n):
	(b, rem, sz) = dec_to_bin(n)
	if rem == 0:
		print(n)
	else:
		print(bin_to_dec(nxt_bin(b, sz)))
	return

def main():
	q = int(input())
	while q:
		q -= 1
		n = int(input())
		solve(n)
	return
main()


three = [1] * 40
pre = [1] * 40
su = 1
for i in range(1, 40):
	three[i] = three[i - 1] * 3
	su += three[i]
	pre[i] = su
for _ in range(int(input())):
	n = int(input())
	ans = 0
	while ans < n:
		i = 0
		while i < 40:
			if ans + pre[i] >= n:
				break
			i += 1
		ans += three[i]
	print(ans)


def main():
	q = int(input())
	for _ in range(q):
		n = int(input())
		sum_pow = 1
		upper_pow = 1
		while sum_pow < n:
			upper_pow *= 3
			sum_pow += upper_pow
		while upper_pow > 0:
			if sum_pow - upper_pow >= n:
				sum_pow -= upper_pow
			upper_pow //= 3
		print(sum_pow)
main()


def mi():
	return map(int, input().split())
mod = 10 ** 9 + 7
from bisect import bisect_right

def ernary(n):
	e = n // 3
	q = n % 3
	if n == 0:
		return '0'
	elif e == 0:
		return str(q)
	else:
		return ernary(e) + str(q)
p = [3 ** i for i in range(40)]
for _ in range(int(input())):
	n = int(input())
	s = list(ernary(n))
	i = 0
	while i < len(s):
		if s[i] == '2':
			i += 1
			while i < len(s):
				s[i] = '0'
				i += 1
		else:
			i += 1
	s = ['0'] + s
	s = s[::-1]
	if '2' in s:
		t = s.index('2')
		s[t] = '0'
		for i in range(t + 1, len(s)):
			if s[i] == '0':
				s[i] = '1'
				break
			if s[i] == '1':
				s[i] = '0'
	s = s[::-1]
	print(int(''.join(s), 3))


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
sys.setrecursionlimit(10 ** 7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
MAX = 0
for i in range(40):
	MAX += 3 ** i
for _ in range(INT()):
	N = INT()
	ans = MAX
	for i in range(39, -1, -1):
		if ans - 3 ** i >= N:
			ans -= 3 ** i
	print(ans)


from bisect import bisect_right

def main():
	a = [3 ** i for i in range(39)]
	stat_sum = [1] + [0] * 38
	for i in range(1, 39):
		stat_sum[i] = stat_sum[i - 1] + a[i]
	q = int(input())
	for _ in range(q):
		n = int(input())
		ans = 0
		while n > 0:
			z = bisect_right(a, n)
			if stat_sum[z - 1] < n:
				ans += a[z]
				break
			else:
				n -= a[z - 1]
				ans += a[z - 1]
		print(ans)
main()


def __DecimalToAnyBaseArrayRecur__(array, decimal, base):
	array.append(decimal % base)
	div = decimal // base
	if div == 0:
		return
	__DecimalToAnyBaseArrayRecur__(array, div, base)

def DecimalToAnyBaseArray(decimal, base):
	array = []
	__DecimalToAnyBaseArrayRecur__(array, decimal, base)
	return ''.join(map(str, array[::-1]))
for _ in range(int(input())):
	n = int(input())
	z = DecimalToAnyBaseArray(n, 3)
	ind2 = -1
	for i in range(len(z)):
		if z[i] == '2':
			ind2 = i
			break
	if ind2 == -1:
		print(n)
	elif '0' not in z:
		print(int('1' + '0' * len(z), 3))
	else:
		ind0 = len(z) + 1
		for i in range(len(z)):
			if i < ind2 and z[i] == '0':
				ind0 = i
		if ind0 < ind2:
			ans = z[:ind0]
			ans += '1'
			ans += '0' * (len(z) - ind0 - 1)
			print(int(ans, 3))
		else:
			print(int('1' + '0' * len(z), 3))


for _ in range(int(input())):
	n = int(input())
	summ = 1
	maxx = 1
	while summ < n:
		maxx *= 3
		summ += maxx
	while maxx > 0:
		if summ - maxx >= n:
			summ -= maxx
		maxx = maxx // 3
	print(summ)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for j in range(int(input())):
	n = int(input())
	temp = 1
	ind = 0
	power = [0 for s in range(40)]
	while n > 0:
		if temp < n:
			temp *= 3
			ind += 1
		else:
			if temp == n:
				n -= temp
				power[ind] += 1
			else:
				n -= temp // 3
				ind -= 1
				power[ind] += 1
			temp = 1
			ind = 0
	maxind = -1
	for s in range(len(power)):
		if power[s] >= 2:
			power[s + 1] = min(2, power[s + 1] + 1)
			maxind = s
			power[s] = 0
	ans = 0
	for s in range(maxind + 1, len(power)):
		if power[s] >= 1:
			ans += 3 ** s
	print(ans)


from math import log, ceil

def cal(x, n):
	p = 3 ** n
	if x == p:
		return p
	elif x == int(p / 2):
		sum = 0
		for y in range(n):
			sum += 3 ** y
		return sum
	elif x > p / 2:
		return p
	else:
		p = 3 ** (n - 1)
		x = x - p if p < x else x
		return p + cal(x, ceil(log(x, 3)))
l = []
n = int(input())
for _ in range(n):
	x = int(input())
	sum = cal(x, ceil(log(x, 3)))
	l.append(sum)
for x in l:
	print(x)


def main():
	q = int(input())
	thirds = [1]
	while thirds[-1] < 1e+19:
		thirds.append(thirds[-1] * 3)
	for t in range(q):
		a = int(input())
		deg = 0
		subans = 0
		while subans < a:
			subans += thirds[deg]
			deg += 1
		while deg != -1:
			if subans - thirds[deg] >= a:
				subans -= thirds[deg]
			deg -= 1
		print(subans)
main()


from math import *
for _ in range(int(input())):
	N = int(input())
	n = N
	if n == 1 or floor(log(n, 3)) == ceil(log(n, 3)) or n == 243:
		print(n)
	elif n < 3:
		print(3)
	else:
		l = []
		flag = 0
		prefix_sum = 0
		ans = 3 ** ceil(log(N, 3))
		while True:
			if n == 243:
				x = 5
			else:
				x = int(log(n, 3))
			prefix_sum += 3 ** x
			l.append([3 ** x, x])
			n = N - prefix_sum
			k = 1
			if len(l) >= 2:
				if l[-2][1] - l[-1][1] >= 2:
					ans = prefix_sum - l[-1][0] + 3 ** (l[-1][1] + 1)
				if l[-2][1] == l[-1][1]:
					flag = 1
					break
			if prefix_sum == N:
				print(N)
				break
		if flag == 1:
			print(min(ans, 3 ** ceil(log(N, 3))))


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
dp = []
i = 0
while True:
	temp = pow(3, i)
	dp.append(temp)
	i += 1
	if temp > 10 ** 18:
		break
for _ in range(int(data())):
	n = int(data())
	s = 0
	index = len(dp) - 1
	for i in range(len(dp)):
		s += dp[i]
		if s >= n:
			index = i
			break
	while index >= 0:
		if s - dp[index] >= n:
			s -= dp[index]
		index -= 1
	out(s)


from sys import stdin, stdout
from math import gcd, sqrt, factorial
from collections import deque, defaultdict
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
lcm = lambda x, y: x * y // gcd(x, y)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 0 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 21
a = []
x = 1
while x <= N:
	a += (x,)
	x *= 3
ln = len(a)
for _ in range(I()):
	n = I()
	v = [0] * ln
	ex = 0
	ans = n
	mx = 0
	while n:
		l = 0
		r = ln - 1
		val = 0
		ind = 0
		while l <= r:
			m = (l + r) // 2
			if a[m] <= n:
				val = a[m]
				ind = m
				l = m + 1
			else:
				r = m - 1
		v[ind] += 1
		mx = max(mx, ind)
		n -= val
	ex = 0
	ans = 0
	for i in range(mx + 2):
		if v[i] > 1:
			ex = 1
		if not v[i] and ex:
			ex -= 1
			v[i] = 1
			ans = 0
		if v[i]:
			ans += a[i]
	print(ans)


T = int(input())
for _ in range(T):
	N = int(input())
	p = 1
	v = 0
	k = 0
	while N > 0:
		r = N % 3
		N = N // 3
		if k == 1:
			if r == 0:
				v = p
				k = 0
			p = p * 3
		elif r == 2:
			k = 1
			p = p * 3
		else:
			v += p * r
			p = p * 3
	if k == 1:
		print(p)
	else:
		print(v)


powers = [1]
n = 0
q = int(input().strip())
for i in range(1, 40):
	powers.append(3 * powers[i - 1])

def lessthan(n):
	ans = 0
	i = 39
	while i >= 0:
		i -= 1
		if powers[i] <= n:
			n -= powers[i]
			ans += powers[i]
	return ans
for case in range(q):
	n = int(input().strip())
	lb = n
	rb = 3 ** 39
	mid = (lb + rb) // 2
	answer = 0
	while lb < rb:
		mid = (lb + rb) // 2
		if lessthan(mid) < n:
			lb = mid + 1
		else:
			answer = lessthan(mid)
			rb = mid
	print(answer)


import math
q = int(input())
for Q in range(q):
	n = int(input())
	tern = []
	t = n
	while t >= 3:
		tern.append(t % 3)
		t = t // 3
	tern.append(t)
	tern.append(0)
	m = -1
	for i in range(len(tern)):
		if tern[i] == 2:
			tern[i] = 0
			m = i
	if m == -1:
		print(n)
	else:
		for i in range(0, m):
			if tern[i] == 1:
				tern[i] = 0
		for i in range(m + 1, len(tern)):
			if tern[i] == 1:
				tern[i] = 0
			elif tern[i] == 0:
				tern[i] = 1
				break
		r = 0
		for i in range(len(tern) - 1, 0, -1):
			r += tern[i]
			r *= 3
		r += tern[0]
		print(r)


n = int(input())
import math
klist = []
for i in range(39):
	klist.append(3 ** i)
for i in range(n):
	p = 0
	x = int(input())
	if x == 1:
		print(1)
	elif x == 2:
		print(3)
	else:
		c = math.log(x, 3)
		d = int(c)
		if x > sum(klist[:d + 1]):
			print(klist[d + 1])
		else:
			for j in range(d):
				if x >= klist[d - j]:
					x -= klist[d - j]
					p += klist[d - j]
				elif x > sum(klist[0:d - j]):
					p += klist[d - j]
					print(p)
					break
				else:
					continue
			if x == 1:
				print(p + 1)
			elif x == 0:
				print(p)


I = lambda : list(map(int, input().split()))
(t,) = I()
p = [1]
while t:
	t -= 1
	(n,) = I()
	ans = n
	p = [3 ** i for i in range(50)]
	x = n
	l = []
	while x > 0:
		k = x % 3
		l.append(k)
		x //= 3
	for i in range(len(l) - 1, -1, -1):
		if l[i] >= 2:
			i += 1
			while i < len(l) and l[i]:
				i += 1
			ans = 3 ** i
			for j in range(i + 1, len(l)):
				if l[j]:
					ans += 3 ** j
			break
	print(ans)


import math
import itertools

def good(num):
	lst = [3 ** i for i in range(math.ceil(math.log(num, 3)) + 1, -1, -1)]
	s = sum(lst)
	for j in lst:
		if s - j >= num:
			s -= j
	return s
for test in range(int(input())):
	print(good(int(input())))


def power(x, y):
	res = 1
	while y > 0:
		if y % 2 == 1:
			res = res * x
		y = y >> 1
		x = x * x
	return res
q = int(input())
for tt in range(q):
	n = int(input())
	s = ''
	temp = n
	while temp > 0:
		s = str(temp % 3) + s
		temp = temp // 3
	index = -1
	i = 0
	while i < len(s):
		if s[i] == '0':
			index = i
		if s[i] == '2':
			break
		i += 1
	if i == len(s):
		print(n)
		continue
	if index == -1:
		print(power(3, len(s)))
		continue
	arr = []
	for i in s:
		arr.append(i)
	arr[index] = '1'
	for i in range(index + 1, len(s)):
		arr[i] = '0'
	ans = 0
	for i in range(len(s)):
		ans = ans * 3 + int(arr[i])
	print(ans)


def build(num, base=38, vetor=[]):
	if base < 0:
		return vetor
	elif num >= 3 ** base:
		return build(num - 3 ** base, base - 1, vetor + [1])
	else:
		return build(num, base - 1, vetor + [0])
q = int(input())
for _ in range(q):
	x = int(input())
	vetor = build(x)
	soma = 0
	for (i, val) in enumerate(vetor[::-1]):
		if val == 1:
			soma += 3 ** i
	if soma == x:
		print(x)
	else:
		vetor = vetor[::-1]
		index = 0
		for i in range(len(vetor)):
			if vetor[i] == 0:
				vetor[i] = 1
				index = i
				break
			else:
				vetor[i] = 0
		vetor = vetor[::-1]
		soma = 0
		for (i, val) in enumerate(vetor[::-1]):
			if val == 1:
				soma += 3 ** i
		print(soma)


import math
t = int(input())
for w in range(t):
	n = int(input())
	c = 0
	while n >= 3:
		a = int(math.log(n, 3)) + 1
		k = (pow(3, a) - 1) // 2
		if n > k:
			c += pow(3, a)
			break
		elif n == k:
			c += k
			break
		else:
			n -= pow(3, a - 1)
			c += pow(3, a - 1)
	if n == 2:
		c += 3
	if n == 1:
		c += 1
	print(c)


def f():
	Q = int(input())
	for q in range(Q):
		n = int(input())
		pow = 0
		while n > 3 ** pow:
			pow += 1
		ans = 0
		while pow >= 0:
			if n <= 0:
				break
			elif (3 ** pow - 1) / 2 >= n:
				pow -= 1
			else:
				n -= 3 ** pow
				ans += 3 ** pow
				pow -= 1
		print(ans)
f()


import sys
sys.setrecursionlimit(10 ** 7)
from collections import deque
import math

def ternaryrepre(n):
	rep = []
	while n > 0:
		rep.append(n % 3)
		n = n // 3
	return rep
powthree = []
aux = 1
for _ in range(39):
	powthree.append(aux)
	aux *= 3
t = int(input())
for _ in range(t):
	n = int(input())
	rep = ternaryrepre(n)
	postwo = -1
	for i in range(len(rep)):
		if rep[i] == 2:
			postwo = i
	if postwo == -1:
		print(n)
	else:
		poszero = -1
		for pos in range(postwo + 1, len(rep)):
			if rep[pos] == 0:
				poszero = pos
				break
		if poszero == -1:
			print(powthree[len(rep)])
		else:
			ans = powthree[poszero]
			for pos in range(poszero + 1, len(rep)):
				if rep[pos]:
					ans += powthree[pos]
			print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)

def ctd(chr):
	return ord(chr) - ord('a')
mod = 998244353
INF = float('inf')

def main():
	arr = [3 ** i for i in range(40)]
	for _ in range(N()):
		n = N()
		sm = sum(arr)
		for i in arr[::-1]:
			if sm - i >= n:
				sm -= i
		print(sm)
main()


l = [3 ** i for i in range(40)]
s = sum(l)
for _ in range(int(input())):
	m = s
	n = int(input())
	for i in l[::-1]:
		if m - i >= n:
			m -= i
	print(m)


import math as m
for i in range(int(input())):
	L = []
	n = int(input())
	k = n
	a = 0
	b = 0
	while n > 0:
		a = int(m.log(n, 3))
		n -= 3 ** a
		L.append(a)
		if a == b:
			break
		b = a
	if len(L) > 1:
		while L[len(L) - 1] == L[len(L) - 2]:
			L.remove(L[len(L) - 1])
			L[len(L) - 1] += 1
			if len(L) == 1:
				break
	o = 0
	for i in L:
		o += 3 ** i
	if k == 2:
		print(3)
	else:
		print(o)


import sys
input = sys.stdin.readline
n = int(input())
for _ in range(n):
	m = int(input())
	originalm = m
	o = []
	while m > 0:
		o.append(m % 3)
		m = m // 3
	o.append(0)
	1
	mcur = 0
	mp = 0
	m3 = 1
	c = 0
	for x in range(len(o)):
		if o[x] == 1:
			mcur += m3
		elif o[x] == 2:
			if c == 1:
				o[x + 1] += 1
			else:
				mp += m3 - mcur
				mcur = 0
				o[x + 1] += 1
		elif o[x] == 3:
			o[x + 1] += 1
		m3 *= 3
	print(mp + originalm)


q = int(input())

def dec_to_base(N, base):
	if not hasattr(dec_to_base, 'table'):
		dec_to_base.table = '0123456789ABCDEF'
	(x, y) = divmod(N, base)
	return dec_to_base(x, base) + dec_to_base.table[y] if x else dec_to_base.table[y]
for i in range(q):
	n = int(input())
	s = list(str(dec_to_base(n, 3)))
	balance = n
	for i in range(len(s) - 1, -1, -1):
		if s[i] == '2':
			balance -= 3 ** (len(s) - i - 1)
			s[i] = '1'
	for i in range(len(s) - 1, -1, -1):
		if balance >= n:
			break
		if s[i] == '0' and balance < n:
			s[i] = '1'
			balance += 3 ** (len(s) - i - 1)
	while balance < n:
		balance *= 3
		s.append('0')
		if balance < n:
			s[-1] = '1'
			balance += 1
		else:
			break
	for i in range(len(s)):
		if balance - 3 ** (len(s) - i - 1) >= n:
			balance -= 3 ** (len(s) - i - 1)
			s[i] = '0'
	print(int(''.join(s), 3))


def func(n):
	s = ''
	while n > 0:
		s = str(n % 3) + s
		n = n // 3
	return s
for q in range(int(input())):
	n = int(input())
	b = func(n)
	s = '0'
	for i in range(len(b)):
		if '0' <= b[i] <= '1':
			s += b[i]
		elif s[-1] == '0':
			s = s[:-1] + '1'
			for j in range(len(b) - len(s) + 1):
				s += '0'
			break
		else:
			j = s.rindex('0')
			s = s[:j] + '1'
			for j in range(len(b) - len(s) + 1):
				s += '0'
			break
	print(int(s, 3))


for q in range(int(input())):
	n = int(input())
	nn = n
	d = []
	while n:
		d.append(n % 3)
		n //= 3
	ln = len(d)
	ind = -1
	for i in range(ln):
		if d[i] == 2:
			ind = i
	if ind == -1:
		print(nn)
		continue
	lone = ind
	while lone + 1 < ln and d[lone + 1] == 1:
		lone += 1
	if lone + 1 == ln:
		d.append(1)
	else:
		d[lone + 1] = 1
	for j in range(lone + 1):
		d[j] = 0
	ans = 0
	pw3 = 1
	ln = len(d)
	for i in range(ln):
		ans += pw3 * d[i]
		pw3 *= 3
	print(ans)


n = int(input())
for i in range(n):
	m = int(input())
	flag = False
	x = m
	while m > 0:
		q = m % 3
		if q == 2:
			flag = True
			break
		m //= 3
	if flag:
		ch = 1
		su = 0
		while ch < x:
			su += ch
			ch *= 3
		if su < x:
			print(ch)
		else:
			while ch > 0:
				if su - ch > x:
					su -= ch
				ch //= 3
			print(su)
	else:
		print(x)


from math import log
for _ in range(int(input())):
	n = int(input())
	s = []
	x = int(log(n, 3))
	while x >= 0:
		if n >= 2 * 3 ** x:
			n -= 2 * 3 ** x
			s.append(2)
		elif n >= 3 ** x:
			n -= 3 ** x
			s.append(1)
		else:
			s.append(0)
		x -= 1
	s = s[::-1]
	l2 = 2229222
	for i in range(len(s)):
		if s[i] == 2:
			l2 = i
	if l2 != 2229222:
		f = 1
		for i in range(len(s)):
			if i <= l2:
				s[i] = 0
			elif s[i] == 0:
				s[i] = 1
				f = 0
				break
			else:
				s[i] = 0
		if f:
			s.append(1)
	ans = 0
	for i in range(len(s)):
		ans += 3 ** i * int(s[i])
	print(ans)


from collections import defaultdict as dc
from collections import deque as dq
from bisect import bisect_left, bisect_right, insort_left
import sys
import math
mod = 10 ** 9 + 7

def bs(a, x):
	i = bisect_left(a, x)
	if i != len(a):
		return i
	else:
		return len(a)

def inp():
	p = sys.stdin.readline()
	return p

def line():
	p = list(map(int, inp().split()))
	return p

def bs(n):
	a = []
	k = 0
	while n > 0:
		if n % 3 == 2:
			k = 1
		a.append(n % 3)
		n = n // 3
	return (a[::-1], k)

def make_number(n):
	z = n % 3
	if z != 0:
		n = 3 * (n // 3)
	return n

def bsl(n):
	p = n
	q = make_number(10 ** 18)
	ans = float('inf')
	while p < q:
		mid = make_number(p + q) // 2
		if bs(mid):
			ans = min(ans, mid)
			q = mid - 3
		else:
			p = mid + 3
		print(p, q, mid)
	print(ans)
for _ in range(int(input())):
	n = int(inp())
	(p, k) = bs(n)
	if k == 0:
		print(n)
	else:
		l = p.index(2)
		p[l:] = [0] * (len(p) - l)
		p = [0] + p
		for i in range(l, -1, -1):
			if p[i] == 0:
				p[i] = 1
				break
			else:
				p[i] = 0
		z = 0
		for i in range(len(p)):
			z = z + pow(3, len(p) - 1 - i) * p[i]
		print(z)


for _ in range(int(input())):
	n = int(input())
	c = 1
	a = []
	while c < n:
		a.append(c)
		c *= 3
	if c == n:
		print(n)
	else:
		k = sum(a)
		if k == n:
			print(k)
		elif k > n:
			for i in a[::-1]:
				if k - i >= n:
					k -= i
			print(k)
		else:
			print(c)


from math import *

def solve():
	n = int(input())
	visited = [0] * 40
	while n > 0:
		x = int(log(n, 3))
		if not visited[x]:
			visited[x] = 1
			n -= 3 ** x
		else:
			x = visited.index(0, x, 40)
			for i in range(x):
				visited[i] = 0
			visited[x] = 1
			n -= 3 ** x
	ans = 0
	for i in range(40):
		if visited[i]:
			ans += 3 ** i
	print(int(ans))
for _ in range(int(input())):
	solve()


for _ in range(int(input())):
	n = int(input())
	power = 1
	num = 1
	while num < n:
		power *= 3
		num += power
	while power >= 1:
		if num - power >= n:
			num -= power
		power //= 3
	print(num)


from sys import stdin

def main():
	aa = [3 ** i for i in range(39)][::-1]
	_s = sum(aa)
	data = list(map(int, stdin.read().splitlines()[1:]))
	for (i, x) in enumerate(data):
		s = _s
		for a in aa:
			if s >= x + a:
				s -= a
		data[i] = str(s)
	print('\n'.join(map(str, data)))
main()


from sys import stdin, setrecursionlimit
setrecursionlimit(10 ** 7)

def iin():
	return int(stdin.readline())

def lin():
	return list(map(int, stdin.readline().split()))
MAX_INT = 99999999

def p3(a):
	ans = []
	while a:
		ans.append(a % 3)
		a //= 3
	return ans

def main():
	t = iin()
	while t:
		t -= 1
		n = iin()
		pw = p3(n) + [0, 0]
		l = len(pw)
		ch = 1
		for i in range(l - 3, -1, -1):
			if pw[i] > 1:
				if ch:
					pw[i] = 0
					pw[i + 1] += 1
					ch = 0
				else:
					pw[i] = 0
			if ch == 0:
				pw[i] = 0
		for i in range(l - 1):
			if pw[i] > 1:
				pw[i] = 0
				pw[i + 1] += 1
		ans = 0
		pw = pw[::-1]
		for i in pw:
			ans = ans * 3 + i
		print(ans)
main()


def d(n, b):
	d.t = '012'
	r = ''
	while n:
		(n, y) = divmod(n, b)
		r = d.t[y] + r
	return r
q = int(input())
for i in range(q):
	n = int(input())
	s = '0' + d(n, 3)
	p = 0
	j = s.find('2')
	if j == -1:
		print(n)
		continue
	jj = s.rfind('0', 0, j)
	s = s[:jj] + '1' + '0' * (len(s) - jj - 1)
	print(int(s, 3))


q = int(input())
n = [int(input()) for i in range(q)]
for ni in n:
	n3 = ''
	while ni > 0:
		p = ni % 3
		if p == 2:
			n3 = '0' * len(n3)
			ni += 1
		else:
			n3 = str(p) + n3
			ni //= 3
	print(int(n3, 3))


import sys

def check(x):
	num = x
	ind = 0
	while True:
		org = x
		s = ''
		done = 1
		while x != 0:
			if x % 3 == 2:
				done = 0
			s = str(x % 3) + s
			x = x // 3
		if done == 1:
			if org == num:
				return num
			break
		c = 0
		for g in range(len(s) - 1, -1, -1):
			if s[g] == '2':
				ind = g
				break
			else:
				c += 1
		tmp = '1' + c * '0'
		x = int(tmp, 3) + org
	arr = []
	for f in range(len(s)):
		arr.append(s[f])
	for p in range(len(s) - 1, ind - 1, -1):
		if arr[p] == '1' and p != ind - 1 and (p != 0):
			arr[p] = '0'
	return int(''.join(arr), 3)
q = int(sys.stdin.readline())
ans_arr = []
for i in range(q):
	n = int(sys.stdin.readline())
	ans = check(n)
	ans_arr.append(str(ans))
print('\n'.join(ans_arr))


def solve(n):
	k = 0
	ans = 0
	while ans + 3 ** k <= n:
		ans += 3 ** k
		k += 1
	if ans < n:
		ans += 3 ** k
	while k > -1:
		if ans - 3 ** k >= n:
			ans -= 3 ** k
		k -= 1
	return ans
for _ in range(int(input())):
	print(solve(int(input())))


import sys

def I():
	return sys.stdin.readline().rstrip()
N = 39
p = [3 ** i for i in range(N)]
q = int(I())
for _ in range(q):
	n = int(I())
	a = [0] * N
	for i in range(N - 1, -1, -1):
		d = n // p[i]
		n -= d * p[i]
		if d == 2:
			j = i + 1
			while a[j]:
				a[j] = 0
				j += 1
			a[j] = 1
			break
		a[i] = d
	n = 0
	for i in range(N):
		if a[i]:
			n += p[i]
	print(n)


a = [3 ** i for i in range(40)]
s = sum(a)
q = int(input())
for _ in range(q):
	n = int(input())
	m = s
	for i in a[::-1]:
		if m - i >= n:
			m -= i
	print(m)


ii = lambda : int(input())
kk = lambda : map(int, input().split())
ll = lambda : list(kk())
for _ in range(ii()):
	n = ii()
	i = 0
	ls = []
	while 3 ** i <= n:
		n2 = n % 3 ** (i + 1)
		ls.append(n2 // 3 ** i)
		i += 1
	i = 0
	i2 = -1
	ls.append(0)
	while i < len(ls):
		(a, b) = (ls[i] // 2, ls[i] % 2)
		if a > 0:
			i2 = i
			ls[i + 1] += a
		ls[i] = b
		i += 1
	if ls[-1] > 1:
		print(3 ** len(ls))
	else:
		k = 0
		for i in range(i2 + 1, len(ls)):
			k += ls[i] * 3 ** i
		print(k)


t = int(input())
while t:
	p = -1
	num = int(input())
	lst = []
	while num > 0:
		lst.append(num % 3)
		if num % 3 == 2:
			p = len(lst)
		num //= 3
	lst.append(0)
	if p > -1:
		ind = lst.index(0, p, len(lst))
		lst[ind] = 1
		for i in range(ind):
			lst[i] = 0
	pw = 0
	ans = 0
	for i in lst:
		ans = ans + 3 ** pw * i
		pw += 1
	print(ans)
	t -= 1


def transfer_to_3(val):
	s = list()
	while val > 0:
		s.append(val % 3)
		val //= 3
	s = ''.join(map(str, s))
	return s[::-1]
n = int(input())
for i in range(0, n):
	x = int(input().strip())
	t = transfer_to_3(x)
	has_2 = False
	for (k, v) in enumerate(t):
		if v is '2':
			if k is 0:
				print(int('1' + '0' * len(t), 3))
			else:
				while k > 0:
					k -= 1
					if t[k] is '0':
						print(int(t[0:k] + '1' + '0' * (len(t) - 1 - k), 3))
						break
				else:
					print(int('1' + '0' * len(t), 3))
			break
	else:
		print(int(t, 3))


t = int(input())
for _ in range(t):
	n = int(input())
	a = 0
	i = 0
	while a < n:
		a += 3 ** i
		i += 1
	for i in range(i, -1, -1):
		if a - 3 ** i >= n:
			a -= 3 ** i
	print(a)


ll = lambda : map(int, input().split())
t = lambda : int(input())
ss = lambda : input()
lx = lambda x: map(int, input().split(x))
for _ in range(t()):
	n = t()
	i = 0
	x = 0
	while x < n:
		x = (3 ** i - 1) // 2
		i += 1
	while x > n and i > 0:
		if x - 3 ** (i - 1) >= n:
			x -= 3 ** (i - 1)
		i -= 1
	print(x)


def ternary(x):
	ans = []
	while x > 0:
		ans.append(x % 3)
		x //= 3
	return ans
q = int(input())
for _ in range(q):
	n = int(input())
	ter = ternary(n)
	ter.append(0)
	if ter.count(2) == 0:
		print(n)
		continue
	idx = 0
	for i in range(len(ter)):
		if ter[i] == 2:
			idx = i
	idt = idx + 1
	for i in range(idx + 1, len(ter)):
		if ter[i] == 0:
			idt = i
			break
	for i in range(idt):
		ter[i] = 0
	ter[idt] = 1
	ter.reverse()
	ans = 0
	for i in ter:
		ans *= 3
		ans += i
	print(ans)


import math
i = 0
s = 0
v = []
while s < 1e+18:
	s += pow(3, i)
	v.append(s)
	i += 1
q = int(input())
for i in range(q):
	n = int(input())
	k = 0
	while v[k] < n:
		k += 1
	ans = v[k]
	l = k
	while l >= 0:
		if ans - pow(3, l) >= n:
			ans -= pow(3, l)
		l -= 1
	print(ans)


def po(a, b):
	if b < 0:
		return 0
	elif b == 0:
		return 1
	x = po(a, b // 2)
	if b % 2 != 0:
		return x * x * a
	return x * x
t = int(input())
for i in range(t):
	n = int(input())
	prev = 0
	while po(3, prev) <= n:
		prev = prev + 1
	ans1 = po(3, prev - 1)
	ans = 0
	n = n - ans1
	k = prev
	while n > 0:
		j = 0
		while po(3, j) <= n:
			j = j + 1
		if j == k:
			ans = ans + po(3, prev)
			break
		else:
			if k - j > 1:
				ans = ans + ans1
				prev = j
				ans1 = 0
			ans1 = ans1 + po(3, j - 1)
			k = j
			n = n - po(3, j - 1)
	if n == 0:
		ans = ans + ans1
	print(ans)


import re

def read(t=int):
	return list(map(t, input().strip().split(' ')))

def go(x):
	stack = []
	while x > 0:
		left = x % 3
		stack.append(left)
		x //= 3
	carry = 0
	carried = 0
	for i in range(len(stack)):
		k = stack[i] + carry
		carry = k // 3
		k = k % 3
		if k == 2:
			k = 0
			carry = 1
			for j in range(i):
				stack[j] = 0
		stack[i] = k
	if carry > 0:
		stack.append(1)
	stack.reverse()
	stack = [str(i) for i in stack]
	s = ''.join(stack)
	return int(s, 3)
q = read()[0]
while q > 0:
	q -= 1
	n = read()[0]
	print(go(n))


l = [0 for i in range(41)]
c = 1
for i in range(1, 41):
	l[i] = l[i - 1] + c
	c *= 3
for _ in range(int(input())):
	n = int(input())
	temp = 0
	for i in range(40, -1, -1):
		if l[i] < n:
			n -= l[i + 1] - l[i]
			temp += l[i + 1] - l[i]
	print(temp)


def base3(n):
	array = []
	while n > 0:
		array.append(n % 3)
		n //= 3
	return array

def good(n):
	return 2 not in base3(n)

def convert(array):
	return sum((array[i] * 3 ** i for i in range(len(array))))
for _ in range(int(input())):
	n = base3(int(input()))
	i = 0
	for i in range(len(n) - 1, -1, -1):
		if n[i] == 2:
			for j in range(i - 1, -1, -1):
				n[j] = 0
			break
	i = 0
	while i < len(n):
		if n[i] > 2:
			if i < len(n) - 1:
				n[i + 1] += n[i] // 3
			else:
				n.append(n[i] // 3)
			n[i] %= 3
		if n[i] == 2:
			if i < len(n) - 1:
				n[i + 1] += 1
			else:
				n.append(1)
			n[i] = 0
		i += 1
	print(convert(n))


l = [1] + [0 for i in range(40)]
for i in range(1, 41):
	l[i] = l[i - 1] * 3
s = [l[0]] + [0 for i in range(40)]
for i in range(1, 41):
	s[i] = s[i - 1] + l[i]
for _ in range(int(input())):
	n = int(input())
	ans = 0
	while ans < n:
		for i in range(41):
			if s[i] + ans >= n:
				ans += l[i]
				break
	print(ans)


for _ in range(int(input())):
	k = n = int(input())
	d = []
	while k:
		d.append(k % 3)
		k //= 3
	if 2 not in d:
		print(n)
		continue
	d.append(0)
	d.reverse()
	last = 0
	for (i, v) in enumerate(d):
		if v == 0:
			last = i
		elif v == 2:
			print(int(''.join(map(str, d[:last])) + '1', 3) * 3 ** (len(d) - last - 1))
			break


powers3 = [3 ** i for i in range(0, 10)]
q = int(input())
for _ in range(q):
	n = int(input())
	n2 = n
	base3 = []
	while n != 0:
		base3.insert(0, n % 3)
		n = n // 3
	for i in range(len(base3) - 1, 0, -1):
		if base3[i] >= 2:
			base3[i] -= 2
			base3[i - 1] += 1
	if base3[0] >= 2:
		base3[0] -= 2
		base3.insert(0, 1)
	count = 0
	for i in range(len(base3) - 1, -1, -1):
		count += base3[len(base3) - i - 1] * 3 ** i
	for i in range(0, len(base3)):
		if base3[i] == 1 and count - 3 ** (len(base3) - i - 1) >= n2:
			count -= 3 ** (len(base3) - i - 1)
	print(count)


import math
import sys
from collections import defaultdict, Counter
from itertools import groupby
rt = lambda : map(int, input().split())
ri = lambda : int(input())
rl = lambda : list(map(int, input().split()))

def main():
	q = ri()
	p3 = [3 ** i for i in range(50)]
	for _ in range(q):
		n = ri()
		x = n
		used = [False] * 50
		for i in range(49, -1, -1):
			if p3[i] <= x:
				used[i] = True
				x -= p3[i]
		if x > 0:
			pos = 0
			while used[pos]:
				pos += 1
			used[pos] = True
			for i in range(pos):
				used[i] = False
			res = 0
			for i in range(50):
				if used[i]:
					res += p3[i]
		else:
			res = n
		print(res)
main()


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
import bisect
import heapq
from math import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def graph(vertex):
	return [[] for i in range(0, vertex + 1)]

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def solve():
	n = int(inp())
	x = 40
	num = 0
	temp = n
	helpp = -1
	new = -1
	f = False
	while temp > 0 and x >= 0:
		if temp < 3 ** x:
			if f:
				new = x
			x -= 1
		else:
			if helpp == -1:
				helpp = x
			f = True
			num += 3 ** x
			temp -= 3 ** x
			x -= 1
	if temp == 0:
		print(num)
	elif x >= 0:
		print(num + 1)
	elif new == -1:
		print(3 ** (helpp + 1))
	else:
		ans = num + 3 ** new
		x = 0
		while x < new:
			ans -= 3 ** x
			x += 1
		print(ans)
testcase(int(inp()))


import sys, math, string, bisect
input = sys.stdin.readline
from collections import deque, defaultdict
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())

def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))

def conv(k):
	c = 0
	for i in range(len(k)):
		c += pow(3, len(k) - i - 1) * int(k[i])
	return c
n = int(input())
for _ in range(n):
	k = I()
	p = ternary(k)
	if p.count('1') + p.count('0') == len(p):
		print(k)
	elif p[0] == '2':
		print(pow(3, len(p)))
	else:
		indexz = 0
		index = 0
		for i in range(len(p)):
			if p[i] == '2':
				index = i
				break
			if p[i] == '0':
				indexz = i
		if indexz != 0:
			print(conv(p[:indexz] + '1' + '0' * (len(p) - indexz - 1)))
		else:
			print(pow(3, len(p)))


q = int(input())
while q:
	q -= 1
	n = int(input())
	t = n
	tern = []
	while t:
		r = t % 3
		tern.append(r)
		t //= 3
	tern.reverse()
	check = -1
	for i in range(len(tern)):
		if tern[i] == 2:
			check = i
			break
	if check == -1:
		print(n)
	else:
		ch = 0
		for i in range(check - 1, -1, -1):
			if tern[i] == 0:
				tern[i] = 1
				ch = 1
				break
			else:
				tern[i] = 0
		if ch:
			s = 0
			tem = len(tern) - 1
			for i in range(check):
				s += tern[i] * 3 ** tem
				tem -= 1
			print(s)
		else:
			print(3 ** len(tern))


def solve():
	x = int(input())
	s = 0
	i = 0
	while s <= x:
		s += 3 ** i
		i += 1
	i -= 1
	while i >= 0:
		if s - 3 ** i >= x:
			s -= 3 ** i
		i -= 1
	return s
q = int(input())
print(*[solve() for i in range(q)], sep='\n')


import math
import sys
import collections
input = sys.stdin.readline

def getdict(n):
	d = {}
	if type(n) is list:
		for i in n:
			if i in d:
				d[i] += 1
			else:
				d[i] = 1
	else:
		for i in range(n):
			t = ii()
			if t in d:
				d[t] += 1
			else:
				d[t] = 1
	return d

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 1
	prime[0] = prime[1] = False
	r = [p for p in range(n + 1) if prime[p]]
	return r

def pow(x, y, mod):
	r = 1
	x = x % mod
	while y > 0:
		if y & 1:
			r = r * x % mod
		y = y >> 1
		x = x * x % mod
	return r

def cdiv(n, k):
	return n // k + (n % k != 0)

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(map(int, input().split()))

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def prr(a, sep=' '):
	print(sep.join(map(str, a)))

def to(n):
	r = []
	while n > 0:
		r.append(n % 3)
		n = n // 3
	r.append(0)
	return r

def fr(l):
	r = 0
	mul = 1
	for i in l:
		r += i * mul
		mul *= 3
	return r
t = ii()
for _ in range(t):
	n = ii()
	d = to(n)
	i = 0
	while i < len(d):
		if d[i] == 2:
			while d[i] != 0:
				i += 1
			d[i] = 1
			for j in range(i - 1, -1, -1):
				d[j] = 0
		i += 1
	print(fr(d))


q = int(input())
for p in range(q):
	n = int(input())
	nn = n
	cnt = 0
	while True:
		if n == 0:
			break
		n /= 3
		cnt += 1
	a = [0] * cnt
	tmp = 0
	j = cnt - 1
	for k in range(cnt):
		i = j - k
		if tmp + 3 ** i <= nn:
			a[i] = 1
			tmp += 3 ** i
	if tmp == nn:
		print(tmp)
	else:
		flag = 0
		tt = 0
		for i in range(cnt):
			if a[i] == 0:
				a[i] = 1
				flag = 1
				tt = i
				break
		if flag == 1:
			ans = 0
			for i in range(cnt):
				if a[i] == 1:
					ans += 3 ** i
			j = tt - 1
			for k in range(tt):
				i = j - k
				if a[i] == 1:
					if ans - 3 ** i >= nn:
						ans -= 3 ** i
			print(ans)
		else:
			print(3 ** cnt)


n3 = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467, 3486784401, 10460353203, 31381059609, 94143178827, 282429536481, 847288609443, 2541865828329, 7625597484987, 22876792454961, 68630377364883, 205891132094649, 617673396283947, 1853020188851841, 5559060566555523, 16677181699666569, 50031545098999707, 150094635296999121, 450283905890997363, 1350851717672992089, 4052555153018976267]
presum = [1, 4, 13, 40, 121, 364, 1093, 3280, 9841, 29524, 88573, 265720, 797161, 2391484, 7174453, 21523360, 64570081, 193710244, 581130733, 1743392200, 5230176601, 15690529804, 47071589413, 141214768240, 423644304721, 1270932914164, 3812798742493, 11438396227480, 34315188682441, 102945566047324, 308836698141973, 926510094425920, 2779530283277761, 8338590849833284, 25015772549499853, 75047317648499560, 225141952945498681, 675425858836496044, 2026277576509488133]
q = int(input())
for _ in range(q):
	n = int(input())
	res = 0
	while n:
		t = n
		cnt = -1
		while t:
			t = t // 3
			cnt += 1
		if n > presum[cnt]:
			res += n3[cnt + 1]
			break
		elif n == presum[cnt]:
			res += presum[cnt]
			break
		else:
			n -= n3[cnt]
			res += n3[cnt]
	print(res)


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import log, ceil

def f(m):
	x = 0
	j = 0
	while m:
		if m & 1:
			x += 3 ** j
		m >>= 1
		j += 1
	return x
for _ in range(int(input())):
	n = int(input())
	(l, r) = (1, 2 ** 42)
	ans = -1
	while l <= r:
		m = l + r >> 1
		if f(m) >= n:
			ans = f(m)
			r = m - 1
		else:
			l = m + 1
	print(ans)


q = int(input())
for i in range(0, q):
	n = int(input())
	l = []
	while n > 0:
		l.append(n % 3)
		n //= 3
	k = len(l)
	pos = 0
	for j in range(-1, -k - 1, -1):
		if l[j] == 2:
			pos = j
			break
	if pos != 0:
		for j in range(pos, -k - 1, -1):
			l[j] = 0
	if pos != 0:
		if pos == -1:
			l.append(1)
			k += 1
		else:
			while pos != -1:
				l[pos + 1] += 1
				if l[pos + 1] < 2:
					break
				l[pos + 1] = 0
				pos += 1
			else:
				l.append(1)
				k += 1
	res = 0
	for j in range(0, k):
		res += 3 ** j * l[j]
	print(res)


for i in range(int(input())):
	n = int(input())
	num = []
	l = 0
	while n > 0:
		num.append(n % 3)
		n //= 3
		l += 1
	num.append(0)
	for j in range(l + 1):
		if num[j] >= 2:
			num[j + 1] += 1
			num[j] = 0
			n = 0
		n += num[j] * 3 ** j
	print(n)


a = [3 ** i for i in range(40)]
x = sum(a)
10 ** 18 < x
for _ in range(int(input())):
	n = int(input())
	x = sum(a)
	for i in a[::-1]:
		if x - i >= n:
			x -= i
	print(x)


for q in range(int(input())):
	n = int(input())
	a = n
	n_in_3 = ''
	while n // 3 != 0:
		n_in_3 += str(n % 3)
		n //= 3
	n_in_3 += str(n % 3) + '0'
	n_in_3 = n_in_3[::-1]
	if '2' not in n_in_3:
		print(a)
	else:
		two = n_in_3.find('2')
		zero = n_in_3[:two].rfind('0')
		a = 0
		for i in range(zero):
			a += int(n_in_3[i]) * 3 ** (len(n_in_3) - i - 1)
		print(a + 3 ** (len(n_in_3) - zero - 1))


import sys
input = sys.stdin.readline
q = int(input())

def calc(n):
	for i in range(40):
		if n <= 3 ** i:
			break
	if n == 3 ** i:
		return n
	elif n > (3 ** i - 1) // 2:
		return 3 ** i
	else:
		n -= 3 ** (i - 1)
		return 3 ** (i - 1) + calc(n)
for testcases in range(q):
	n = int(input())
	print(calc(n))


max_powers = 50
powers = [3 ** i for i in range(max_powers)]
p = [0 for i in range(max_powers + 1)]
for i in range(1, max_powers + 1):
	p[i] = p[i - 1] + powers[i - 1]
for _ in range(int(input())):
	n = int(input())
	i = max_powers
	while i >= 0 and p[i] > n:
		i -= 1
	i += 1
	ans = p[i]
	while i >= 0 and i < max_powers:
		if ans - powers[i] >= n:
			ans -= powers[i]
		i -= 1
	print(ans)


import sys
input = sys.stdin.buffer.readline
from collections import defaultdict
INF = float('inf')

def getlist():
	return list(map(int, input().split()))

def main():
	Q = int(input())
	for i in range(Q):
		N = int(input())
		X = []
		n = N
		while True:
			X.append(n % 3)
			n = int(n // 3)
			if n == 0:
				break
		X.append(0)
		st = 0
		for i in range(len(X) - 1):
			if X[i] == 2:
				st = i
				X[i] = 0
				if X[i + 1] == 0:
					X[i + 1] = 1
				else:
					X[i + 1] = 2
		ans = 0
		for i in range(st, len(X)):
			if X[i] == 1:
				ans += 3 ** i
		print(ans)
main()


def r():
	return map(int, input().split())

def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))
t = int(input())
for _ in range(t):
	n = int(input())
	y = ternary(n)
	if '2' in y:
		val = '1' * len(y)
		if int(val, 3) < n:
			print(3 ** len(y))
		else:
			v = list(val)
			for i in range(1, len(val)):
				temp = list(v)
				temp[i] = '0'
				if int(''.join(temp), 3) >= n:
					v = list(temp)
			print(int(''.join(v), 3))
	else:
		print(n)


import sys
from bisect import bisect
inp = sys.stdin.readline
ans = ''
powers = [3 ** i for i in range(39)]
for _ in range(int(inp())):
	n = int(inp())
	i = 38
	while powers[i] > n and i >= 0:
		i -= 1
	if powers[i] != n:
		maxi = powers[i + 1]
		b = i + 1
	else:
		maxi = powers[i]
		b = i
	sume = 0
	while i >= 0:
		sume += powers[i]
		if sume >= n:
			maxi = min(maxi, sume)
			sume -= powers[i]
		i -= 1
	ans += str(min(maxi, powers[b])) + '\n'
print(ans)


def bin2(n):
	l = []
	while n > 0:
		l.append(n % 2)
		n = n // 2
	l.reverse()
	return l

def bin3(n):
	l = []
	while n > 0:
		l.append(n % 3)
		n = n // 3
	l.reverse()
	return l

def num2(l):
	ans = 0
	for i in l:
		ans = ans * 2 + i
	return ans

def num3(l):
	ans = 0
	for i in l:
		ans = ans * 3 + i
	return ans
t = int(input())
for you in range(t):
	n = int(input())
	l = bin3(n)
	poss = 1
	for i in l:
		if i == 2:
			poss = 0
			break
	if poss:
		print(n)
		continue
	n = len(l)
	for i in range(n):
		if l[i] == 2:
			for j in range(i, n):
				l[j] = 1
			break
	z = num2(l)
	z += 1
	l = bin2(z)
	print(num3(l))


import sys
input = sys.stdin.readline
q = int(input())
for _ in range(q):
	m = int(input())
	n = m
	sansin = []
	while True:
		sansin.append(n % 3)
		n //= 3
		if n < 3:
			sansin.append(n)
			break
	f = 1
	x = 0
	for i in range(len(sansin)):
		if sansin[i] == 2:
			f = 0
			x = i
	if f:
		print(m)
	else:
		sansin.insert(len(sansin), 0)
		ans = 0
		ff = 1
		for i in range(x, len(sansin)):
			if sansin[i] == 0 and ff:
				ans += 3 ** i
				ff = 0
			elif ff == 0:
				ans += sansin[i] * 3 ** i
		print(ans)


t = int(input())
while t > 0:
	n = int(input())
	arr = []
	ans = 0
	i = 0
	while ans < n:
		k = 3 ** i
		ans = ans + k
		arr.append(k)
		i = i + 1
	for j in reversed(arr):
		if ans - j >= n:
			ans = ans - j
	t = t - 1
	print(ans)


def to_base_3(x):
	l = []
	while x:
		(x, r) = divmod(x, 3)
		l.append(str(r))
	return ''.join(reversed(l))
t = int(input())
for i in range(t):
	n = int(input())
	base_3_num = to_base_3(n)
	if '2' not in base_3_num:
		print(n)
		continue
	index_2 = base_3_num.find('2')
	index_0 = -1
	for i in range(0, index_2):
		if base_3_num[i] == '0':
			index_0 = i
	if index_2 < index_0 or index_0 == -1:
		print(int('1' + '0' * len(base_3_num), 3))
	else:
		print(int(base_3_num[0:index_0] + '1' + '0' * len(base_3_num[index_0 + 1:]), 3))


pot3 = [1]
for _ in range(39):
	pot3.append(pot3[-1] * 3)
t = int(input())
for _ in range(t):
	n = int(input())
	l = 0
	r = (1 << 39) - 1
	ans = 0
	while r - l > 1:
		w = l + (r - l) // 2
		res = 0
		for i in range(39):
			if w & 1 << i:
				res += pot3[i]
		if res < n:
			l = w
		else:
			r = w
			ans = res
	print(ans)


def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))
for _ in range(int(input())):
	n = int(input())
	x = list('0' + ternary(n))
	if '2' in x:
		for i in range(x.index('2')):
			if x[i] == '0':
				z = i
		x[z] = '1'
		for i in range(z + 1, len(x)):
			x[i] = '0'
		ans = 0
		for i in range(len(x)):
			ans += int(x[i]) * pow(3, len(x) - 1 - i)
		print(ans)
	else:
		print(n)


from functools import reduce as rd
import operator as optr
import math
import itertools
for _ in range(int(input())):
	n = int(input())
	v = []
	for i in range(0, 39):
		v.append(3 ** i)
	m = n
	add = 0
	indx = 0
	for i in range(0, 39):
		add += v[i]
		if add > n:
			indx = i
			break
	visited = [0] * 40
	i = indx
	while i >= 0:
		if n >= v[i]:
			n -= v[i]
			visited[i] = 1
		i -= 1
	if n == 0:
		print(m)
	else:
		flag = 0
		inn = 0
		for j in range(0, indx):
			if visited[j] != 1:
				flag = 1
				inn = j
				break
			else:
				m -= v[j]
		if flag == 1:
			print(m + v[inn] - n)
		else:
			print(v[indx])


import math
nm3 = list()
pw3 = list()
for i in range(39):
	pw3.append(pow(3, i))
for _ in range(int(input())):
	n = int(input())
	sm = 0
	i = 0
	while sm < n:
		sm += pw3[i]
		i += 1
	i -= 1
	while i >= 0:
		if sm - pw3[i] >= n:
			sm -= pw3[i]
		i -= 1
	print(sm)


from sys import exit as sys_return
queries = int(input())
while queries != 0:
	queries -= 1
	number = int(input())
	(numbers, copy, max_, i) = ([0] * 100, number, -1, 0)
	while copy != 0:
		if copy % 3 == 2:
			max_ = max(max_, i)
		numbers[i] += copy % 3
		numbers[i + 1] += (numbers[i] + 1) // 3
		numbers[i] %= 2
		copy //= 3
		i += 1
	if max_ == -1:
		print(number)
		continue
	for i in range(0, max_ + 1):
		numbers[i] = 0
	for i in range(max_ + 1, len(numbers) - 1):
		numbers[i + 1] += (numbers[i] + 1) // 3
		numbers[i] %= 2
	new_number = 0
	for i in range(len(numbers)):
		new_number += numbers[i] * 3 ** i
	print(new_number)


from math import log

def get_num(strr):
	total = 0
	n = len(strr)
	for i in range(n - 1, -1, -1):
		if strr[n - 1 - i] == '1':
			total += 3 ** i
	return total

def solve(n):
	org = n
	bits = int(log(n, 3))
	bnr = ['0'] * (bits + 1)
	for i in range(bits, -1, -1):
		temp = n - pow(3, i)
		if temp == 0:
			return org
		if temp > 0:
			n = temp
			bnr[bits - i] = '1'
	bin_num = int(''.join(bnr), 2) + 1
	return get_num(str(bin(bin_num))[2:])
t = int(input())
for _ in range(t):
	n = int(input())
	if n <= 2:
		print(pow(3, n - 1))
	else:
		ans = solve(n)
		print(ans)


for _ in range(int(input())):
	n = int(input())
	save = n
	a = []
	p2 = -1
	p = 0
	while n > 0:
		temp = n % 3
		n = n // 3
		if temp == 2:
			p2 = p
		p += 1
		a.append(temp)
	if p2 == -1:
		print(save)
	else:
		a.append(0)
		index = a.index(0, p2, p + 1)
		for i in range(index):
			a[i] = 0
		a[index] = 1
		ans = 0
		e = 1
		for i in range(p + 1):
			ans += e * a[i]
			e *= 3
		print(ans)


import math
trial = int(input())
while trial:
	trial -= 1
	n = int(input())
	sum_s = 0
	idx = 0
	while sum_s < n:
		sum_s += 3 ** idx
		idx += 1
	while idx:
		idx -= 1
		if sum_s - 3 ** idx >= n:
			sum_s -= 3 ** idx
	print(sum_s)


T = int(input())
dp = []
for i in range(0, 64):
	dp.append(3 ** i)
for i in range(T):
	n = int(input())
	N = 0
	for j in dp:
		N += j
	for j in range(0, 64):
		if N - dp[63 - j] >= n:
			N -= dp[63 - j]
	print(N)


q = int(input())
for i in range(q):
	n = int(input())
	rev3 = []
	a = n
	while 1:
		rev3.append(a % 3)
		a //= 3
		if a // 3 == 0:
			break
	rev3.append(a)
	for j in range(40):
		rev3.append(0)
	for j in range(len(rev3)):
		if rev3[j] == 2:
			n += 3 ** j
			rev3[j + 1] += 1
			rev3[j] = 0
			for k in range(j):
				n -= 3 ** k * rev3[k]
				rev3[k] = 0
		if rev3[j] == 3:
			rev3[j + 1] += 1
			rev3[j] = 0
	print(n)


def binaryTernary():
	from sys import stdin
	q = int(stdin.readline().strip())
	for _ in range(q):
		n = int(stdin.readline().strip())
		(lo, hi) = (1, n)
		ans = None
		while lo <= hi:
			mid = lo + (hi - lo) // 2
			t = int(bin(mid)[2:], 3)
			if t >= n:
				ans = t
				hi = mid - 1
			else:
				lo = mid + 1
		print(ans)
binaryTernary()


N = 38

def f(x):
	ret = 0
	for i in range(N + 1):
		if x >> i & 1:
			ret += 3 ** i
	return ret

def solve():
	n = int(input())
	(ng, ok) = (-1, 1 << N)
	while ok - ng > 1:
		mid = (ok + ng) // 2
		if f(mid) >= n:
			ok = mid
		else:
			ng = mid
	return f(ok)

def main():
	q = int(input())
	for _ in range(q):
		print(solve())
main()


q = int(input())
for _ in range(q):
	n = int(input())
	decomp = []
	while n != 0:
		decomp.append(n % 3)
		n = n // 3
	(push, lastpush) = (0, -1)
	for i in range(len(decomp)):
		decomp[i] += push
		push = 0
		if decomp[i] >= 2:
			(push, lastpush) = (1, i)
	decomp.append(push)
	s = 0
	for (put, val) in enumerate(decomp):
		if put > lastpush:
			s += val * 3 ** put
	print(s)


q = int(input())
for loop in range(q):
	n = int(input())
	n_sub = n
	lis = []
	while n > 0:
		lis.append(n % 3)
		n = n // 3
	lis.reverse()
	las0 = None
	las2 = None
	if 2 not in lis:
		print(n_sub)
		continue
	slis = []
	now = 0
	for i in range(len(lis)):
		if lis[i] == 1:
			now += 3 ** (len(lis) - 1 - i)
		elif lis[i] == 0:
			slis.append(now + 3 ** (len(lis) - 1 - i))
		elif len(slis) == 0:
			print(3 ** len(lis))
			break
		else:
			print(slis[-1])
			break


q = int(input())

def to_triple(n):
	ans = []
	while n > 0:
		ans.append(n % 3)
		n = n // 3
	return ans + [0]

def finder(ans):
	s = 0
	for i in range(len(ans)):
		if ans[i] > 1:
			ans[i + 1] += 1
			s = 0
		else:
			s += 3 ** i * ans[i]
	return s
for _ in range(q):
	n = int(input())
	print(finder(to_triple(n)))


q = int(input())
for p in range(q):
	n = int(input())
	s = []
	while n > 0:
		s.append(n % 3)
		n //= 3
	s.append(0)
	for i in range(len(s) - 1, -1, -1):
		if s[i] == 2:
			s[i] += 1
			for j in range(i, len(s)):
				if s[j] == 2:
					s[j] += 1
				if s[j] >= 3:
					s[j + 1] += 1
					s[j] = s[j] % 3
			for j in range(i):
				s[j] = 0
	k = 1
	n = 0
	for a in s:
		n += a * k
		k *= 3
	print(n)


tc = int(input())

def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return list(reversed(nums))
while tc > 0:
	tc -= 1
	n = int(input())
	rep = ['0'] + ternary(n)
	idx = -1
	for i in range(len(rep)):
		if rep[i] == '2':
			idx = i - 1
			while rep[idx] != '0':
				idx -= 1
			rep[idx] = '1'
			for j in range(idx + 1, len(rep)):
				rep[j] = '0'
	ans = 0
	for j in rep:
		x = ord(j) - ord('0')
		ans = ans * 3 + x
	print(ans)


import sys
import math

def f():
	n = int(input())
	a = []
	n2 = n + 0
	for i in range(round(math.log(n, 3)), -1, -1):
		if 3 ** i > n2:
			continue
		a.append(n // 3 ** i)
		n %= 3 ** i
	over = 0
	add = 0
	x = len(a)
	ind = -1
	for i in range(x):
		if a[i] == 2:
			ind = i
			break
	if ind == -1:
		print(n2)
		return
	add2 = 0
	for i in range(ind + 1, x):
		if a[i] == 2:
			add2 += 3 ** (x - i - 1) * 2
		elif a[i] == 1:
			add2 += 3 ** (x - i - 1)
	add = 3 ** (x - ind - 1)
	ind -= 1
	while ind >= 0 and a[ind] == 1:
		add += 3 ** (x - ind - 1)
		ind -= 1
	print(n2 + add - add2)
for _ in range(int(input())):
	f()


import sys, math
I = sys.stdin.readline
ans = ''
for _ in range(int(I())):
	n = int(I())
	x = math.floor(math.log(n, 3))
	a = [3 ** i for i in range(x + 1)]
	a.reverse()
	if sum(a) >= n:
		total = 0
		flag = 1
		for i in range(len(a)):
			if total + a[i] <= n:
				total += a[i]
				if total == n:
					flag = 0
					break
		if flag:
			total = 0
			c = set()
			for i in range(len(a)):
				if total + a[i] < n:
					total += a[i]
				elif total + a[i] > n:
					c.add(total + a[i])
			total = min(c)
		ans += '{}\n'.format(total)
	else:
		ans += '{}\n'.format(3 ** math.floor(math.log(n, 3) + 1))
print(ans)


cnt = 1
t = [0] * 60
for i in range(60):
	t[i] = cnt
	cnt *= 3

def th(n, d):
	if n <= 2:
		return '0' * (d - 1) + str(n)
	global t
	i = 0
	while t[i] <= n:
		i += 1
	i -= 1
	return '0' * (d - 1 - i) + str(n // t[i]) + th(n % t[i], i)
for q in range(int(input())):
	n = int(input())
	a = th(n, 60)
	if a.count('2') == 0:
		print(n)
		continue
	i = 0
	while a[i] != '2':
		i += 1
	while a[i] != '0':
		i -= 1
	b = a[:i] + '1' + '0' * (60 - i - 1)
	cnt = 0
	for i in range(60):
		cnt += (ord(b[59 - i]) - ord('0')) * t[i]
	print(cnt)


def fat(n):
	arr = []
	while n > 0:
		arr.append(n % 3)
		n //= 3
	return arr
t = int(input())
for _ in range(t):
	n = int(input())
	nfat = fat(n)
	c = 0
	for i in range(len(nfat)):
		nfat[i] += c
		if nfat[i] > 1:
			for j in range(i + 1):
				nfat[j] = 0
			c = 1
		else:
			c = 0
	if c == 1:
		nfat.append(1)
	p = 1
	x = 0
	for i in nfat:
		x += i * p
		p *= 3
	print(x)


def trans(x, k):
	string = ''
	while x != 0:
		(u, v) = divmod(x, k)
		string = str(v) + string
		x = u
	return string

def check(string):
	for i in range(len(string)):
		if string[i] == '2':
			return i
			break
	return -1

def check2(string, index):
	for i in range(index, -1, -1):
		if string[i] == '0':
			return i
			break
	return -1

def main():
	q = int(input())
	for i in range(q):
		n = int(input())
		string = list(trans(n, 3))
		index = check(string)
		if index < 0:
			print(n)
		else:
			index2 = check2(string, index)
			if index2 < 0:
				print(3 ** len(string))
			else:
				string[index2] = '1'
				ans = 0
				for i in range(index2 + 1):
					ans += int(string[i]) * 3 ** (len(string) - 1 - i)
				print(ans)
main()


from math import *
t = int(input())
a = []
k = 1
for i in range(38):
	a.append(k)
	k *= 3
a.append(k)
for y in range(t):
	ct = [0 for i in range(39)]
	n = int(input())
	n1 = n
	while n != 0:
		for i in range(39):
			if a[i] >= n:
				j = i - 1
				break
		if a[j + 1] == n:
			ct[j + 1] += 1
			n = 0
		else:
			n -= a[j]
			ct[j] += 1
	l = -1
	key = 0
	for i in range(39):
		if ct[i] == 0:
			if l == -1:
				l = i
		elif ct[i] == 2:
			ct[i] = 1
			l = -1
			key = 1
	ans = a[l]
	if l == -1 or key == 0:
		print(n1)
	else:
		for i in range(l, 39):
			ans += ct[i] * a[i]
		print(ans)


num_queries = int(input())
for _ in range(num_queries):
	n = int(input())
	m = 0
	power = 0
	while m < n:
		m += 3 ** power
		power += 1
	while power >= 0:
		m2 = m - 3 ** power
		if m2 < n:
			m2 = m
			power -= 1
			continue
		m = m2
		power -= 1
	print(m)


for test in range(int(input())):
	n = int(input())
	m = n
	n_3 = []
	while n:
		n_3.append(n % 3)
		n //= 3
	ind = len(n_3)
	flag = True
	for i in range(len(n_3) - 1, -1, -1):
		if n_3[i] == 2:
			break
		if n_3[i] == 0:
			flag = False
			ind = i
	if 2 in n_3:
		if flag:
			print(3 ** len(n_3))
		else:
			ans = 0
			for i in range(len(n_3) - 1, -1, -1):
				if i == ind or n_3[i] == 1:
					ans += 3 ** i
				if n_3[i] == 2 or i == ind:
					break
			print(ans)
	else:
		print(m)


import sys
from heapq import heapify, heappop, heappush
from itertools import *
from collections import *
from math import *
sys.setrecursionlimit(10 ** 6)
input = lambda : sys.stdin.readline()
inp = lambda : int(input())
nm = lambda : map(int, input().split())
arr = lambda : list(nm())
INF = int(1e+18)
mod = int(1000000000.0) + 7
TT = inp()
t = 1
lst = [0] * 50
for i in range(50):
	lst[i] = t
	t *= 3
summ = sum(lst)
for y in range(TT):
	n = inp()
	temp = summ
	for i in range(49, -1, -1):
		if temp - lst[i] >= n:
			temp -= lst[i]
	print(temp)


from math import ceil, log
pows = []
for i in range(41):
	pows.append(3 ** i)
for i in range(40):
	pows[i + 1] += pows[i]
q = int(input())
for _ in range(q):
	n = int(input())
	for (i, v) in enumerate(pows):
		if v > n:
			lb = pows[i]
			lbidx = i
			break
	ub = 3 ** ceil(log(n, 3))
	if n > lb:
		print(ub)
	else:
		ans = 0
		for i in range(lbidx, -1, -1):
			p2 = 3 ** i
			if n == 0:
				break
			elif n >= p2:
				ans += p2
				n -= p2
			else:
				p1 = pows[i - 1]
				p2 = 3 ** i
				if n > p1:
					ans += p2
					break
				else:
					continue
		print(ans)


for _ in range(int(input())):
	x = int(input())
	s = []
	while x != 0:
		s.append(x % 3)
		x //= 3
	s.append(0)
	for n in range(len(s) - 1, -1, -1):
		if s[n] == 2:
			idx = n
			while s[idx] != 0:
				idx += 1
			s[idx] = 1
			for j in range(idx):
				s[j] = 0
			break
	res = 0
	for n in range(len(s)):
		res += s[n] * 3 ** n
	print(res)


for i in range(int(input())):
	n = int(input())
	a = []
	while n:
		a.append(n % 3)
		n //= 3
	a = a + [0]
	for i in range(len(a) - 1):
		if a[i] >= 2:
			a[i] = 0
			a[i + 1] += 1
			if a[i + 1] == 1:
				for i in range(i, -1, -1):
					a[i] = 0
	if a[-1] == 1:
		for i in range(len(a) - 1):
			a[i] = 0
	ans = 0
	x = 1
	for i in range(len(a)):
		ans += a[i] * x
		x *= 3
	print(ans)


q = int(input())
for u in range(q):
	n = int(input())
	newNum = ''
	while n > 0:
		newNum = str(n % 3) + newNum
		n //= 3
	newN = ['0']
	for i in range(len(newNum)):
		newN.append(str(newNum[i]))
	while '2' in set(newN):
		k = len(newN)
		for i in range(1, k + 1):
			if newN[-i] == '2':
				newN[-i] = '0'
				if newN[-1 - i] == '0':
					newN[-1 - i] = '1'
				elif newN[-1 - i] == '1':
					newN[-1 - i] = '2'
				for x in range(1, i):
					newN[-x] = '0'
	a = 1
	test = 0
	for i in range(1, len(newN) + 1):
		test += int(newN[-i]) * a
		a *= 3
	print(test)
	newN.clear()
	test = 0


isVerbose = False

def v(msg):
	if isVerbose:
		print(msg)
q = int(input())
while q:
	n = int(input())
	b3 = []
	while n:
		b3.append(n % 3)
		n //= 3
	b3.append(0)
	b3.reverse()
	last_0 = 0
	for i in range(len(b3)):
		if b3[i] == 0:
			last_0 = i
		elif b3[i] > 1:
			b3[last_0] = 1
			b3[last_0 + 1:] = map(lambda x: 0, b3[last_0 + 1:])
	b3.reverse()
	out = 0
	for i in range(len(b3)):
		out += b3[i] * 3 ** i
	print(out)
	q -= 1


q = int(input())
for b in range(q):
	n = int(input())
	i = 0
	L = []
	L2 = []
	L3 = []
	somme = 0
	while 1:
		L.append(3 ** i)
		i += 1
		if 3 ** i > n:
			break
	x = 3 ** i
	for j in range(len(L)):
		somme += L[len(L) - j - 1]
		if somme >= n:
			L2.append(somme)
			somme -= L[len(L) - j - 1]
	if len(L2) > 0:
		print(min(L2))
	else:
		print(x)


def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(r)
	return nums
q = int(input())
while q > 0:
	q -= 1
	n = int(input())
	s = ternary(n)
	for i in range(len(s) - 1):
		if s[i] >= 2:
			s[i + 1] += 1
			s[i] = 0
	if s[len(s) - 1] >= 2:
		s = [0 for i in range(len(s))]
		s.append(1)
	ans = 0
	for i in range(len(s)):
		if s[i] == 1:
			ans += 3 ** i
	for i in range(len(s)):
		if s[i] == 1:
			if ans - 3 ** i >= n:
				ans -= 3 ** i
			else:
				break
	print(ans)


q = int(input())
arr = []
cur = 1
for _ in range(40):
	arr.append(cur)
	cur *= 3
arr = arr[::-1]
s = sum(arr)
for _ in range(q):
	n = int(input())
	ans = s
	for i in arr:
		if ans - i >= n:
			ans -= i
	print(ans)


for n in range(int(input())):
	x = int(input())
	s = []
	while x:
		s.append(x % 3)
		x //= 3
	carry = 0
	s.append(0)
	for n in range(len(s) - 1, -1, -1):
		if s[n] == 2:
			cur = n
			while s[cur]:
				cur += 1
			s[cur] = 1
			for k in range(cur):
				s[k] = 0
	sm = 0
	for n in range(len(s)):
		sm += s[n] * 3 ** n
	print(sm)


q = int(input())
for _ in range(q):
	n = int(input())
	A_s = 0
	i = 0
	while A_s < n:
		A_s += 3 ** i
		i += 1
	while i >= 0:
		if A_s - 3 ** i >= n:
			A_s -= 3 ** i
		i -= 1
	print(A_s)


a = [1 for i in range(40)]
b = [1 for i in range(40)]
t = 3
for i in range(1, 100):
	if a[i - 1] > 1e+18:
		break
	b[i] = t
	t *= 3
	a[i] = int((t - 1) / 2)
for _ in range(int(input())):
	n = int(input())
	ans = 0
	cnt = 40
	while n > 0:
		for i in range(cnt):
			if a[i] >= n:
				break
		cnt = i
		n -= b[i]
		ans += b[i]
	print(ans)


def good_numbers(n: int) -> int:
	base_three_inverted = []
	while n > 0:
		remainder = n % 3
		base_three_inverted.append(remainder)
		n = n // 3
	for i in range(len(base_three_inverted)):
		digit = base_three_inverted[i]
		if digit > 1:
			for j in range(i + 1):
				base_three_inverted[j] = 0
			if i < len(base_three_inverted) - 1:
				base_three_inverted[i + 1] += 1
			else:
				base_three_inverted.append(1)
	acc = 0
	for i in range(len(base_three_inverted)):
		digit = base_three_inverted[i]
		acc += digit * 3 ** i
	return acc

def test():
	assert good_numbers(1) == 1
	assert good_numbers(2) == 3
	assert good_numbers(6) == 9
	assert good_numbers(13) == 13
	assert good_numbers(14) == 27
	assert good_numbers(3620) == 6561
	assert good_numbers(10000) == 19683
q = int(input())
for _ in range(q):
	n = int(input())
	print(good_numbers(n))


def ceillog(num, base):
	n = num
	res = 0
	while n >= base:
		n //= base
		res += 1
	if base ** res == num:
		return res
	else:
		return res + 1
for _ in range(int(input())):
	n = int(input())
	dp = []
	for i in range(ceillog(n, 3) + 1):
		dp.append(3 ** i)
	chk = sum(dp)
	while chk > n and dp:
		if chk - dp[-1] < n:
			dp.pop()
		else:
			chk -= dp[-1]
			dp.pop()
	print(chk)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9
for _ in range(int(input())):
	n = int(input())
	a = []
	copy = n
	while n > 0:
		a.append(n % 3)
		n //= 3
	pos2 = -1
	a.append(0)
	for i in range(len(a)):
		if a[i] > 1:
			pos2 = i
	if pos2 == -1:
		print(copy)
		continue
	pos1 = 0
	for i in range(pos2 + 1, len(a)):
		if a[i] == 0:
			a[i] = 1
			pos1 = i
			break
	n = 0
	for i in range(pos1, len(a)):
		n += a[i] * 3 ** i
	print(n)


def add_my_bit(t, s):
	if t[s] == 2:
		t[s] = 0
		if s == len(t) - 1:
			t.append(1)
		else:
			add_my_bit(t, s + 1)
	elif t[s] == 1:
		t[s] = 2
	elif t[s] == 0:
		t[s] = 1
	return t

def make_me_short(t):
	w = t[::-1].index(2)
	if len(t) - w <= len(t) - 1 and t[len(t) - w] == 0:
		t[len(t) - w] = 1
		for rv in range(len(t[:len(t) - w])):
			t[rv] = 0
		flag = True
	else:
		flag = False
	return flag
fk = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467, 3486784401, 10460353203, 31381059609, 94143178827, 282429536481, 847288609443, 2541865828329, 7625597484987, 22876792454961, 68630377364883, 205891132094649, 617673396283947, 1853020188851841, 5559060566555523, 16677181699666569, 50031545098999707, 150094635296999121, 450283905890997363, 1350851717672992089, 4052555153018976267]
for _ in range(int(input())):
	a = int(input())
	lm_1 = a
	n = a
	t = []
	k = 0
	while a != 0:
		t.append(a % 3)
		a = a // 3
	u = len(t)
	if 2 in t:
		while 2 in t and len(t) == u:
			if 2 in t:
				make_me_short(t)
			if 2 in t:
				p = t[::-1].index(2)
				add_my_bit(t, len(t) - p - 1)
		v = len(t)
		if u < v:
			k = fk[v - 1]
		elif not make_me_short:
			for j in range(len(t)):
				k = k + fk[j] * t[j]
			for w in range(lm_1, k + 1):
				lm_0 = w
				rd = []
				while w != 0:
					rd.append(w % 3)
					w = w // 3
				if 2 not in rd:
					qr = lm_0
					k = qr
					break
		else:
			for j in range(len(t)):
				k = k + fk[j] * t[j]
	else:
		k = n
	print(k)


def convert_base(num, to_base=10, from_base=10):
	if isinstance(num, str):
		n = int(num, from_base)
	else:
		n = int(num)
	alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
	if n < to_base:
		return alphabet[n]
	else:
		return convert_base(n // to_base, to_base) + alphabet[n % to_base]
for q in range(int(input())):
	n = int(input())
	s = convert_base(n, 3, 10)
	index = -1
	minindex = len(s) + 100
	for i in range(0, len(s)):
		if int(s[i]) > 1:
			index = i
			if index < minindex:
				minindex = index
	if index == -1:
		print(n)
	else:
		if index == 0:
			s = '1' + '0' * len(s)
		else:
			l = list(s)
			pb = False
			for i in range(index, -1, -1):
				if l[i] == '2' or l[i] == '3':
					l[i] = '0'
					if i - 1 >= 0:
						l[i - 1] = ascii(int(l[i - 1]) + 1)
					else:
						pb = True
			if pb:
				s = '1' + '0' * len(s)
			else:
				for i in range(minindex, len(l)):
					l[i] = '0'
				s = ''
				for i in l:
					s += i
		print(convert_base(s, 10, 3))


from sys import stdin

def func(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))
q = int(stdin.readline())
for i in range(q):
	n = int(stdin.readline())
	m = func(n)
	l = len(m)
	if '2' not in m:
		print(n)
	else:
		for i in range(l):
			if m[i] == '2':
				break
			else:
				pass
		m = m[0:i + 1]
		ans = []
		for ele in m:
			ans.append(int(ele))
		if len(ans) == 1:
			arr = ['1', '0']
			for j in range(l - i - 1):
				arr.append('0')
		else:
			ans[-1] = 0
			carry = 1
			for j in range(len(m) - 2, -1, -1):
				ans[j] = (ans[j] + carry) % 2
				if ans[j] == 0:
					pass
				else:
					carry = 0
			if carry == 1:
				arr = ['1']
			else:
				arr = []
			for ele in ans:
				arr.append(str(ele))
			for j in range(l - len(m)):
				arr.append('0')
		s = ''.join(arr)
		f = 0
		s = s[::-1]
		for i in range(len(s)):
			f += 3 ** i * int(s[i])
		print(f)


t = 40
ps = [1] * t
su = [1] * t
for i in range(1, t):
	ps[i] = ps[i - 1] * 3
	su[i] = su[i - 1] + ps[i]

def jud(n):
	for i in range(t):
		if su[i] >= n:
			st = i
			cur = su[i]
			break
	for i in range(st, -1, -1):
		if cur - ps[i] >= n:
			cur -= ps[i]
	return cur
q = int(input())
for _ in range(q):
	print(jud(int(input())))


import sys, math

def main():
	for _ in range(int(sys.stdin.readline().strip())):
		n = int(sys.stdin.readline().strip())
		m = n
		skip = 38
		for i in range(38, -1, -1):
			if 3 ** i <= m:
				m -= 3 ** i
			else:
				skip = i
		if m <= 0:
			sys.stdout.write(str(n) + '\n')
		else:
			ans = 0
			m = n
			for i in range(38, -1, -1):
				if i == skip:
					ans += 3 ** i
					break
				if 3 ** i <= m:
					m -= 3 ** i
					ans += 3 ** i
			sys.stdout.write(str(ans) + '\n')
main()


q = int(input())
N = [int(input()) for i in range(q)]
t = [3 ** i for i in range(10)]

def d(x):
	ans = 0
	m = 1
	while x > 0:
		if x % 2 == 1:
			ans += m
		m *= 3
		x //= 2
	return ans
for i in range(q):
	n = N[i]
	m = 0
	t = 0
	l = 0
	r = 2 ** 50
	mid = (l + r) // 2
	while r - l > 1:
		m = d(mid)
		if m >= n:
			r = mid
		else:
			l = mid
		mid = (l + r) // 2
	print(d(l + 1))


arr = []
for i in range(40):
	arr.append(3 ** i)
n = int(input())
for i in range(n):
	sb = [0] * 40
	a = int(input())
	x = a
	xx = a
	for j in range(39, -1, -1):
		if a - arr[j] >= 0:
			a -= arr[j]
			sb[j] = 1
	x = x - a
	if a == 0:
		print(x)
		continue
	for j in range(40):
		if sb[j] == 0:
			x = x + 3 ** j
			break
		else:
			x = x - 3 ** j
	print(x)


ct = int(input())
for c in range(ct):
	n = input()
	aux = int(n)
	li = []
	while aux >= 3:
		li.append(aux % 3)
		aux //= 3
	li.append(aux)
	li.append(0)
	if li.count(2) >= 1:
		index = len(li) - list(reversed(li)).index(2) - 1
		for i in range(0, index):
			li[i] = 0
		for i in range(index, len(li)):
			if li[i] >= 2:
				li[i] += 1
				li[i + 1] += li[i] // 3
				li[i] %= 3
	print(int(''.join(reversed([str(i) for i in li])), 3))


import sys

def extract_factors(number, base):
	current_power = 1
	powers = []
	while current_power <= number:
		powers.append(current_power)
		current_power *= base
	factors = []
	for power in reversed(powers):
		factor = 0
		while number >= power:
			number -= power
			factor += 1
		factors.append(factor)
	return reversed(factors)

def sum_factors(factors, base):
	multiplier = 1
	total = 0
	for factor in factors:
		total += factor * multiplier
		multiplier *= base
	return total

def biggest_smaller_power(number, base):
	factors = [i for i in extract_factors(number, base)]
	good_limit = 1
	good_factors = []
	carry = 0
	for factor in factors:
		factor += carry
		carry = 0
		if factor > good_limit:
			carry = 1
			good_factors = [0] * (len(good_factors) + 1)
		else:
			good_factors.append(factor)
	if carry:
		good_factors.append(carry)
	return sum_factors(good_factors, base)

def test():
	assert 1 == biggest_smaller_power(1, 3)
	assert 3 == biggest_smaller_power(2, 3)
	assert 9 == biggest_smaller_power(6, 3)
	assert 13 == biggest_smaller_power(13, 3)
	assert 27 == biggest_smaller_power(14, 3)
	assert 6561 == biggest_smaller_power(3620, 3)
	assert 19683 == biggest_smaller_power(10000, 3)
n = int(input())
for __ in range(n):
	m = int(input())
	print(biggest_smaller_power(m, 3))


BS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def to_base(s, b):
	res = ''
	while s:
		res += BS[s % b]
		s //= b
	return res[::-1] or '0'
t = int(input())
for i in range(t):
	n = int(input())
	b = str(to_base(n, 3))[::-1]
	b += '0' * 10
	b = list(b)
	for i in range(len(b)):
		if b[i] == '2':
			b[i] = '0'
			j = i + 1
			while True:
				if b[j] == '0':
					b[j] = '1'
					break
				else:
					b[j] = '0'
				j += 1
			b[:j] = '0' * len(b[:j])
	b = ''.join(b)[::-1]
	tot = 0
	for k in range(len(b) - 1, -1, -1):
		tot += 3 ** (len(b) - 1 - k) * int(b[k])
	print(tot)


maxn = 39

def solve():
	p = []
	p.append(1)
	tmp = 1
	for i in range(maxn):
		tmp = tmp * 3
		p.append(tmp)
	return p
p3 = solve()
q = int(input())
while q:
	q = q - 1
	n = int(input())
	l = 0
	r = 2 ** maxn
	ans = 0
	while r - l > 1:
		mid = (l + r) // 2
		t = 0
		for i in range(maxn):
			t = t + (mid >> i & 1) * p3[i]
		if t >= n:
			r = mid
			ans = t
		else:
			l = mid
	print(ans)


import math

def find_good_number(n):
	current_good = 3 ** 0
	k = 1
	while current_good < n:
		current_good += 3 ** k
		k += 1
	if current_good == n:
		return n
	power_to_start = int(math.log(current_good - n, 3))
	for i in reversed(range(power_to_start + 2)):
		diff = current_good - n
		if 3 ** i > diff:
			continue
		current_good -= 3 ** i
	return current_good
q = int(input())
for _ in range(q):
	n = int(input())
	print(find_good_number(n))


for _ in [0] * int(input()):
	n = int(input())
	s = ''
	i = j = 0
	while n:
		s = str(n % 3) + s
		n //= 3
	s = '0' + s
	i = s.find('2')
	r = 0
	if i + 1:
		k = s.rfind('0', 0, i)
		s = s[:k] + '1' + '0' * (len(s) - k - 1)
	for c in s:
		r = r * 3 + int(c)
	print(r)


from math import *
q = int(input())
while q:
	q -= 1
	n = int(input())
	nn = n
	pows = [0] * 40
	while n > 0:
		t = int(log(n, 3))
		if pows[t]:
			t = pows.index(0, t, 40)
			for i in range(t):
				pows[i] = 0
			pows[t] = 1
			n -= 3 ** t
		else:
			pows[t] = 1
			n -= 3 ** t
	ans = 0
	flag = 0
	for i in range(40):
		if pows[i]:
			ans += 3 ** i
	print(ans)


for i in range(int(input())):
	n = int(input())
	c = 1
	co = 0
	a = []
	while c < n:
		co += 1
		a.append(c)
		c *= 3
	if c == n:
		print(n)
	elif sum(a) >= n:
		if sum(a) == n:
			print(n)
		else:
			t = sum(a)
			for i in range(len(a) - 1, -1, -1):
				if t - a[i] >= n:
					t = t - a[i]
			print(t)
	else:
		print(c)


def bit(n, k):
	return n // 3 ** k % 3

def solve():
	n = int(input())
	INF = 10 ** 30
	dp = [[INF for _ in range(2)] for __ in range(50)]
	dp[49][0] = 0
	for ii in range(49):
		i = 50 - 2 - ii
		b = bit(n, i)
		if b < 2:
			dp[i][0] = dp[i + 1][0] + b * 3 ** i
		dp[i][1] = dp[i + 1][1]
		if b == 0:
			dp[i][1] = min(dp[i][1], dp[i + 1][0] + 3 ** i)
	print(min(dp[0]))
	return
q = int(input())
for _ in range(q):
	solve()


A = [3 ** i for i in range(40)]
m = sum(A)
t = int(input())
for _ in range(t):
	n = int(input())
	x = m
	for p in A[::-1]:
		if x - p >= n:
			x -= p
	print(x)


def t(n):
	f = ''
	while n:
		(n, r) = divmod(n, 3)
		f += str(r)
	return '0' + f[::-1]
for _ in range(int(input())):
	n = int(input())
	s = '0' + t(n)
	if s.count('2'):
		k = len(s)
		ans = 0
		g = s.index('2')
		for i in range(g):
			if s[i] == '0':
				zind = i
		ans = 3 ** (k - zind - 1)
		for i in range(zind):
			ans += int(s[i]) * 3 ** (k - i - 1)
		print(ans)
	else:
		print(n)


n = int(input())
for queries in range(n):
	base_3 = []
	num = int(input())
	original_num = num
	remainder = 0
	first_two = 0
	while num != 0:
		remainder = num % 3
		num = num // 3
		base_3.append(remainder)
	base_3.reverse()
	if 2 in base_3:
		first_two = base_3.index(2)
		if 0 in base_3[:first_two]:
			last_zero = first_two - 1 - base_3[:first_two][::-1].index(0)
			base_3[last_zero] = 1
			count = 0
			for i in range(last_zero + 1):
				count += 3 ** (len(base_3) - 1 - i) * base_3[i]
			print(count)
		else:
			print(3 ** len(base_3))
	else:
		print(original_num)


for tc in [0] * int(input()):
	n = int(input())
	arr = []
	i = 0
	while sum(arr) < n:
		k = 3 ** i
		arr.append(k)
		i = i + 1
	ans = sum(arr)
	for j in arr[::-1]:
		if ans - j >= n:
			ans -= j
	print(ans)


def main():
	q = int(input())
	for _ in [0] * q:
		n = int(input())
		nn = n
		res = [0] * 50
		p = pow(3, 49)
		idx = 49
		ma = -1
		while n != 0:
			if n >= p:
				pr = n // p
				res[idx] = pr
				n -= pr * p
				if pr == 2 and ma == -1:
					ma = idx
			p = p // 3
			idx -= 1
		for i in range(ma, 50):
			if res[i] == 2:
				res[i] = 0
				res[i + 1] += 1
		if ma == -1:
			print(nn)
		else:
			ans = 0
			p = pow(3, 49)
			idx = 49
			while idx >= ma:
				if res[idx] == 1:
					ans += p
				p = p // 3
				idx -= 1
			print(ans)
main()


a = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467, 3486784401, 10460353203, 31381059609, 94143178827, 282429536481, 847288609443, 2541865828329, 7625597484987, 22876792454961, 68630377364883, 205891132094649, 617673396283947, 1853020188851841, 5559060566555523, 16677181699666569, 50031545098999707, 150094635296999121, 450283905890997363, 1350851717672992089]
sum3 = 2026277576509488133
for _ in range(int(input())):
	ans = sum3
	n = int(input())
	for x in a[::-1]:
		if ans - x >= n:
			ans -= x
	print(ans)


def f(n):
	s = ''
	while n:
		y = n % 3
		n = n // 3
		s += str(y)
	return s[::-1]
q = int(input())
while q:
	q -= 1
	n = int(input())
	s = list(f(n))
	u = len(s)
	ans = ''
	for i in range(u - 1, -1, -1):
		if s[i] == '1' or s[i] == '0':
			ans += s[i]
		else:
			ans += '0'
			s[i - 1] = str(ord(s[i - 1]) - ord('0') + 1)
	if s[0] == '2' or s[0] == '3':
		ans += '1'
	out = 0
	if len(ans) > u:
		out += pow(3, len(ans) - 1)
	else:
		for i in range(len(ans) - 1, -1, -1):
			if out >= n:
				break
			out += pow(3, i) * (ord(ans[i]) - ord('0'))
	print(out)


def iss(m):
	while m > 0:
		if m % 3 == 2:
			return False
		if m % 3 == 1:
			m -= 1
		else:
			m = m // 3
	return True

def good_num(m):
	arr = []
	i = 0
	p = m
	while m > 0:
		if m % 3 == 2:
			arr.append(i)
			m -= 1
			continue
		if m % 3 == 1:
			m -= 1
			arr.append(i)
		else:
			m = m // 3
			i += 1
	num = 0
	for i in range(len(arr) - 1):
		if arr[i + 1] <= arr[i]:
			if i + 1 == len(arr) - 1:
				num = 0
				arr[i + 1] += 1
				break
			arr[i + 1] += 1
			num = 0
			continue
		num += 3 ** arr[i]
	num += 3 ** arr[-1]
	return num
q = int(input().strip())
while q > 0:
	m = int(input().strip())
	print(good_num(m))
	q -= 1


t = int(input())
while t != 0:
	n = int(input())
	tri = []
	while n != 0:
		tri.append(n % 3)
		n = n // 3
	for i in range(0, len(tri)):
		if tri[i] >= 2:
			mark = True
			j = i + 1
			while True:
				if j >= len(tri):
					tri.append(1)
					break
				if tri[j] == 0:
					tri[j] = 1
					break
				tri[j] = 0
				j += 1
			for j in range(0, i + 1):
				tri[j] = 0
	ans = 0
	for i in range(0, len(tri)):
		ans += tri[i] * pow(3, i)
	print(ans)
	t -= 1


d = []
for i in range(40):
	d.append(3 ** i)
s = sum(d)
t = int(input())
for tt in range(t):
	n = int(input())
	m = s
	for i in d[::-1]:
		if m - i >= n:
			m -= i
	print(m)


def check(q):
	temp = []
	while q > 0:
		m = q % 3
		q = q - m
		q = q // 3
		temp.append(m)
	flag = -1
	for i in range(len(temp)):
		if temp[i] == 2:
			temp[i] = 0
			flag = i
	if flag == -1:
		return temp
	else:
		for i in range(flag + 1):
			temp[i] = 0
		for i in range(flag + 1, len(temp)):
			if temp[i] == 0:
				temp[i] = 1
				break
			else:
				temp[i] = 0
		else:
			temp.append(1)
		return temp
t = int(input())
for _ in range(t):
	q = int(input())
	s = check(q)
	num = 0
	for i in range(len(s)):
		num += s[i] * pow(3, i)
	print(int(num))


import sys
lines = sys.stdin.readlines()
q = int(lines[0])
for i in range(1, q + 1):
	n = int(lines[i])
	(i, max_i) = (0, 0)
	while 3 ** i <= n:
		if n % 3 ** (i + 1) >= 2 * 3 ** i:
			n += 3 ** i
			max_i = i
		i += 1
	n -= n % 3 ** max_i
	print(n)


for _ in range(int(input())):
	a = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467, 3486784401, 10460353203, 31381059609, 94143178827, 282429536481, 847288609443, 2541865828329, 7625597484987, 22876792454961, 68630377364883, 205891132094649, 617673396283947, 1853020188851841, 5559060566555523, 16677181699666569, 50031545098999707, 150094635296999121, 450283905890997363, 1350851717672992089]
	n = int(input())
	if n in a:
		print(n)
	else:
		t = []
		for i in range(39):
			if a[i] > n:
				t.append(a.pop(i - 1))
				r = n - t[0]
				s = a[i - 1]
				break
		while r >= a[0] or r == 0:
			if r == 0:
				print(n)
				break
			for i in range(39):
				if a[i] > r:
					r = r - a[i - 1]
					t.append(a.pop(i - 1))
					break
		if r != 0:
			num = t[0] + a[0]
			while num < n:
				num += t.pop(1)
			print(min(num, s))


lst = [3 ** i for i in range(40)]
s = sum(lst)
for t in range(int(input())):
	(n, x) = (int(input()), s)
	for i in lst[::-1]:
		if x - i >= n:
			x -= i
	print(x)


Q = int(input())
for q in range(Q):
	N = int(input())
	st = ''
	while N:
		mod = N % 3
		N = N // 3
		st = chr(48 + mod + 7 * (mod > 10)) + st
	l = len(st)
	for i in range(l - 1, 0, -1):
		if int(st[i]) > 1:
			st = st[:i - 1] + str(int(st[i - 1]) + 1) + '0' * (l - i)
	if int(st[0]) > 1:
		st = '1' + '0' * l
	final = 0
	k = 0
	for j in range(len(st) - 1, -1, -1):
		final += int(st[j]) * 3 ** k
		k += 1
	print(final)


tar = []
for i in range(40):
	tmp = 3 ** i
	tar.append(tmp)
sum_num = sum(tar)
tar = list(reversed(tar))
from bisect import *
Q = int(input())
for q in range(Q):
	N = int(input())
	tar2 = tar.copy()
	ans = sum_num
	idx = -1
	for (i, t) in enumerate(tar2):
		if ans - t >= N:
			ans -= t
			continue
	print(ans)


from collections import deque
for i in range(int(input())):
	n = int(input())
	three = deque()
	tol = 0
	while n:
		t = n % 3
		three.appendleft(str(t))
		tol += 1
		n //= 3
	for j in range(tol - 1, -1, -1):
		if three[j] == '2':
			for q in range(j, tol):
				three[q] = '0'
			flag = 0
			for k in range(j - 1, -1, -1):
				if three[k] == '0':
					three[k] = '1'
					flag = 1
					break
				else:
					three[k] = '0'
			if flag == 0:
				three.appendleft('1')
				tol += 1
	res = 0
	a = 0
	for j in range(tol - 1, -1, -1):
		res += int(three[j]) * 3 ** a
		a += 1
	print(res)


n = int(input())
for i in range(n):
	c = []
	t = int(input())
	p = t
	while p:
		c.append(p % 3)
		p = p // 3
	d = 0
	for i in range(len(c) - 1, -1, -1):
		if d == 1:
			break
		if c[i] == 2:
			t = 0
			for j in range(i + 1, len(c)):
				if c[j] == 0:
					c = [0] * j + [1] + c[j + 1:]
					d = 1
					break
			else:
				c = [0] * len(c) + [1]
				break
	p = 0
	for i in range(len(c)):
		p += c[i] * 3 ** i
	print(p)


def to_ternary(x):
	rp = []
	for p in range(40)[::-1]:
		rp.append(x // 3 ** p)
		x = x % 3 ** p
	return rp[::-1]

def from_ternary(rp):
	x = 0
	for i in range(40):
		x += rp[i] * 3 ** i
	return x
for i in range(int(input())):
	n = int(input())
	n = to_ternary(n)
	zero = 0
	for i in range(40):
		if n[i] >= 2:
			for j in range(zero, i):
				n[j] = 0
			n[i] = 0
			zero = i
			n[i + 1] += 1
	n = from_ternary(n)
	print(n)


from math import *
from sys import *
from heapq import *
from collections import defaultdict
from itertools import permutations
import os, sys
from io import IOBase, BytesIO
M = 10 ** 9 + 7

def graph_as_tree_1_root():
	n = int(input())
	dict = defaultdict(list)
	for _ in range(n - 1):
		(x, y) = list(map(int, input().split()))
		dict[x].append(y)
		dict[y].append(x)
	tree = [[1]]
	temp = [1]
	vall = 0
	seen = set([i for i in range(2, n + 1)])
	lol = []
	while len(seen) > 0:
		lol = list(seen)
		tt = []
		for x in temp:
			aa = []
			for val in dict[x]:
				if val in seen:
					aa += [val]
					seen.remove(val)
			dict[x] = aa
			tt += aa
		tree.append(tt)
		temp = tt
		vall += 1
	for x in lol:
		dict[x] = []
	print(tree, dict)

def pow(a, b):
	res = 1
	while b > 0:
		if b & 1:
			res *= a
		a *= a
		b >>= 1
	return res

def powmod(a, b, m):
	res = 1
	while b > 0:
		if b & 1:
			res = res * a % m
		a = a * a % m
		b //= 2
	return res

def inv(a, m):
	return powmod(a, m - 2, m)

def alldivisors(n):
	list = []
	arr = []
	for i in range(1, int(sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				arr += [i]
			else:
				arr += [i]
				list.append(n // i)
	arr += list[::-1]
	return arr

def primefactorisation(n):
	potentional_p = 3
	itog_list = defaultdict(int)
	if n % 2 == 0:
		itog_list[2] = 0
	while n % 2 == 0:
		n = n // 2
		itog_list[2] += 1
	while n - 1:
		if potentional_p > n ** 0.5:
			itog_list[n] += 1
			return itog_list
		while n % potentional_p == 0:
			n = n // potentional_p
			itog_list[potentional_p] += 1
		potentional_p += 2
	return itog_list

def meth(x):
	lst = []
	while x > 0:
		val = int(log(x, 3))
		lst = [val] + lst
		x -= 3 ** val
	if len(lst) == 3 and lst[0] == lst[1] == lst[2]:
		return [lst[0]]
	return lst

def modi(lst):
	if len(lst) == 1:
		return lst
	fin = []
	nn = len(lst)
	temp = []
	for i in range(nn - 1):
		if lst[i + 1] - lst[i] >= 2:
			temp += [lst[i]]
			fin.append(temp)
			temp = []
		else:
			temp += [lst[i]]
	if temp != []:
		fin.append(temp)
	if lst[-1] - lst[-2] >= 2:
		fin.append([lst[-1]])
	else:
		fin[-1].append(lst[-1])
	return fin

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		lst = meth(n)
		if len(lst) == len(set(lst)):
			print(n)
			continue
		res = 0
		flag = 0
		for lst in modi(lst)[::-1]:
			if len(lst) == 1:
				res += 3 ** lst[0]
				continue
			nn = len(lst)
			fl = 0
			for i in range(nn - 1):
				if lst[i + 1] - lst[i] == 0:
					fl = 1
					break
			if fl == 1:
				res += 3 ** (1 + lst[-1])
				flag = 1
			else:
				for x in lst:
					res += 3 ** x
			if flag == 1:
				break
		print(res)
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import math
q = int(input())
memo = {}

def mem(n):
	if n < 1:
		return 0
	elif n == 1:
		return 1
	elif n in memo:
		return memo[n]
	else:
		x = int(math.log(n, 2))
		y = 3 ** x
		z = 2 ** x
		memo[n] = y + mem(n - z)
		return memo[n]
for _ in range(q):
	n = int(input())
	low = 0
	high = 10 ** 18
	while low <= high:
		mid = (low + high) // 2
		if mem(mid - 1 + 1) < n and mem(mid + 1) >= n:
			break
		elif mem(mid - 1 + 1) >= n:
			high = mid - 1
		elif mem(mid + 1) <= n:
			low = mid + 1
	print(mem(mid + 1))


q = int(input())
for i in range(q):
	n = int(input())
	nn = n
	nnn = n
	res = 0
	li = [0] * 100
	mx = -1
	l = []
	while nn:
		cou = 0
		n = nn
		while n:
			n = n // 3
			if n:
				cou += 1
		li[cou] = 1
		if mx == -1:
			mx = cou
		a = 3 ** cou
		l.append(cou)
		nn -= a
	l.sort()
	j = 0
	lol = 0
	mxx = 0
	for i in l:
		if i >= mxx:
			if li[i] != 2:
				li[i] = 2
			elif li[i] == 2:
				j = i
				while li[j]:
					j += 1
				if j > mx:
					lol = 1
					mx = j
					break
				else:
					li[j] = 2
					if j > mxx:
						mxx = j
	su = 0
	if lol:
		print(3 ** j)
	else:
		for i in range(0, mx + 1):
			if li[i] == 2 and i >= mxx:
				su += 3 ** i
		if su == 0:
			print(nnn)
		else:
			print(su)


def bin(a):
	x = ''
	while a:
		x += str(a % 3)
		a //= 3
	return x[-1::-1]
x = 10 ** 18
pre = [1]
while pre[-1] <= x:
	pre.append(pre[-1] * 3)
q = int(input())
for _ in range(q):
	n = int(input())
	aa = list(bin(n))
	aa = [int(i) for i in aa]
	x = len(aa)
	z = -1
	ans = aa[:]
	for i in range(len(aa)):
		if aa[i] == 0:
			z = max(z, i)
		if aa[i] == 2:
			if z == -1:
				ans = [1] + [0 for i in range(x)]
			else:
				ans = ans[:z] + [1] + [0 for i in range(z + 1, x)]
			break
	tot = 0
	for i in range(len(ans)):
		if ans[-i - 1] == 1:
			tot += pre[i]
	print(tot)


a = [3 ** i for i in range(39)]
for _ in range(int(input())):
	n = int(input())
	ans = 0
	for i in range(38, -1, -1):
		if n - a[i] >= 0:
			n -= a[i]
			ans += a[i]
		elif n - a[i] < 0 and (3 ** i - 1) // 2 < n:
			n -= a[i]
			ans += a[i]
	print(ans)


q = int(input())
p3 = []
p3.append(1)
for i in range(40):
	p3.append(p3[-1] * 3)
while q > 0:
	q -= 1
	x = int(input())
	cur = 0
	nums = [0] * 40
	while x > 0:
		if x % 3 == 1:
			if nums[cur] == 1:
				nums[cur] = 0
				nums[cur + 1] = 1
			else:
				nums[cur] = 1
		if x % 3 == 2:
			for i in range(cur + 1):
				nums[i] = 0
			nums[cur + 1] = 1
		x //= 3
		cur += 1
	ans = 0
	for i in range(40):
		ans += nums[i] * p3[i]
	print(ans)


def Solve(n):
	Di = {}
	save = n
	j = FindPow(n)
	ma = j
	b = False
	while n > 0:
		if j in Di.keys():
			Di[j] += 1
			b = True
		else:
			Di[j] = 1
		n -= int(pow(3, j))
		j = FindPow(n)
	if not b:
		return save
	data = [0] * (ma + 2)
	for j in Di.keys():
		data[j] = Di[j]
	i = len(data) - 1
	while i >= 0:
		if data[i] >= 2:
			for k in range(i):
				data[k] = 0
			break
		i -= 1
	for j in range(i, len(data) - 1):
		if data[j] == 2:
			data[j] = 0
			data[j + 1] += 1
		elif data[j] == 3:
			data[j] = 0
			data[j + 1] += 1
	s = 0
	k = 1
	for x in range(len(data)):
		s += k * data[x]
		k *= 3
	return s

def FindPow(n):
	s = 0
	j = n
	while n > 1:
		s += 1
		n = n // 3
	if pow(3, s) > j:
		return s - 1
	return s
t = int(input())
while t > 0:
	t -= 1
	print(Solve(int(input())))


t = int(input())
for karai in range(t):
	m = int(input())
	x = 1
	s = 0
	p3 = []
	s3 = []
	for i in range(50):
		p3.append(x)
		s3.append(s)
		s += x
		x *= 3
	res = 0
	for i in reversed(range(49)):
		if s3[i] < m:
			m -= p3[i]
			res += p3[i]
	print(res)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
cases = int(input())
for t in range(cases):
	n = int(input())
	out = []
	while n:
		r = n % 3
		out.append(r)
		n //= 3
	lo = len(out)
	pos = -1
	for i in range(lo):
		if out[i] == 2:
			pos = i
	if pos == -1:
		print(sum([pow(3, i) for i in range(lo) if out[i] == 1]))
	else:
		out.append(0)
		for i in range(pos, lo):
			if out[i] == 2:
				out[i] = 0
				out[i + 1] += 1
		print(sum([pow(3, i) for i in range(pos + 1, lo + 1) if out[i] == 1]))


t = int(input())
a = []
for i in range(t):
	n = int(input())
	a.append(n)
for i in a:
	j = i
	l = []
	while j != 0:
		r = j % 3
		j = j // 3
		l.append(r)
	p = -1
	q = -1
	for j in range(len(l)):
		if l[j] == 2:
			p = j
		if l[j] == 0:
			q = j
	if p > q:
		print(3 ** len(l))
	elif q == -1 or p == -1:
		print(i)
	else:
		v = 0
		o = 0
		for m in range(p + 1, len(l)):
			if l[m] == 0 and o == 0:
				v += 3 ** m
				o = 1
			elif o == 1 and l[m] == 1:
				v += 3 ** m
		print(v)


q = int(input())
threelist = []
i = 0
while 3 ** i < 10 ** 18:
	threelist.append(3 ** i)
	i += 1
threelist.append(3 ** i)
for _ in range(q):
	n = int(input())
	j = 0
	sum = 0
	while n > sum:
		sum += threelist[j]
		j += 1
	for k in range(j - 1, -1, -1):
		if sum - threelist[k] >= n:
			sum -= threelist[k]
	print(sum)


def solve(q):
	rep = []
	while q:
		rem = q % 3
		rep.append(rem)
		q //= 3
	rep.append(0)
	i = 0
	while i < len(rep):
		if rep[i] == 2:
			rep[i] = 0
			for j in range(i + 1, len(rep)):
				if rep[j] == 0:
					rep[j] = 1
					for k in range(j):
						rep[k] = 0
					i = j
					break
		i += 1
	ans = 0
	for (i, num) in enumerate(rep):
		ans += num * 3 ** i
	return ans
t = int(input())
for _ in range(t):
	n = int(input())
	print(solve(n))


def po(a, b):
	if b < 0:
		return 0
	elif b == 0:
		return 1
	x = po(a, b // 2)
	if b % 2 != 0:
		return x * x * a
	return x * x
t = int(input())
for i in range(t):
	n = int(input())
	l = []
	for j in range(40):
		l.append(0)
	while n != 0:
		j = 0
		while po(3, j) <= n:
			j = j + 1
		if l[j - 1] == 1:
			while l[j - 1] == 1:
				l[j - 1] = 0
				j = j + 1
			l[j - 1] = 1
			ans = 0
			j = 0
			while j < 40:
				if l[j] == 1:
					ans = ans + po(3, j)
				j = j + 1
			break
		else:
			l[j - 1] = 1
			n = n - po(3, j - 1)
	if n == 0:
		ans = 0
		j = 0
		while j < 40:
			if l[j] == 1:
				ans = ans + po(3, j)
			j = j + 1
	print(ans)


for _ in range(int(input())):
	l = int(input())
	(k, n) = ([], l)
	while n > 0:
		k += [n % 3]
		n //= 3
	x = len(k)
	n = 0
	if 2 not in k:
		print(l)
	else:
		c = 0
		for i in range(x):
			j = (k[i] + c) % 3
			if c == 1 and k[i] == 0:
				n = 3 ** i
				c = 0
				k[i] = 1
			else:
				c = (k[i] + c) // 3
				k[i] = j
				if j == 2:
					l += 3 ** i
					c = 1
					k[i] = 0
				n = n + 3 ** i if k[i] else n
		if c != 0:
			l = 3 ** x
			n = 3 ** x
			k.append(c)
		print(n)


q = int(input())

def ternary(n):
	out = []
	c = n
	while c > 0:
		[d, z] = divmod(c, 3)
		out.append(z)
		c = d
	out.reverse()
	return out

def decimal(t):
	out = 0
	for j in range(len(t)):
		out = t[j] + 3 * out
	return out
for i in range(q):
	n = int(input())
	tern = ternary(n)
	last_zero = -1
	my_ind = len(tern) + 100
	for j in range(len(tern)):
		if tern[j] == 1:
			continue
		elif tern[j] == 0:
			last_zero = j
			continue
		else:
			my_ind = j
			break
	if my_ind == len(tern) + 100:
		print(n)
	elif last_zero == -1:
		print(3 ** len(tern))
	else:
		tern[last_zero] = 1
		tern[last_zero + 1:] = (len(tern) - last_zero - 1) * [0]
		print(decimal(tern))


def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))

def C1():
	answer = ''
	for q in range(int(input())):
		num = int(input())
		tern_num = ternary(num)
		bigger_power_of_three = '1' + '0' * len(tern_num)
		good_num = bigger_power_of_three
		last_0 = -1
		index = 0
		good_num = tern_num
		for digit in tern_num:
			if digit == '0':
				last_0 = index
			elif digit == '2':
				if last_0 == -1:
					good_num = bigger_power_of_three
				else:
					good_num = tern_num[0:last_0] + '1' + (len(tern_num[last_0:]) - 1) * '0'
				break
			index += 1
		good_num = int(good_num, 3)
		answer += str(good_num) + '\n'
	print(answer)
C1()


L = []
for i in range(0, 39):
	L.append(3 ** i)
q = int(input())
for _ in range(q):
	n = int(input())
	ans = 0
	while n > 0:
		ptr = 38
		for i in range(0, len(L)):
			if L[i] > n:
				ptr = i
				break
		if n > (L[ptr] - 1) / 2:
			ans += L[ptr]
			break
		else:
			n -= L[ptr - 1]
			ans += L[ptr - 1]
	print(ans)


def three(x):
	s = ''
	while x:
		s = str(x % 3) + s
		x //= 3
	s = '0' + s
	i = s.find('2')
	if i > 0:
		j = s[:i].rfind('0')
		s = s[:j] + '1' + '0' * (len(s) - j - 1)
	r = 0
	s = s[::-1]
	for i in range(len(s)):
		r += int(s[i]) * 3 ** i
	return r
n = int(input())
for i in range(n):
	print(three(int(input())))


arr = [3 ** i for i in range(40)]
total = sum(arr)
for _ in range(int(input())):
	n = int(input())
	m = total
	for i in arr[::-1]:
		if m - i >= n:
			m -= i
	print(m)


tc = int(input())
for _ in range(tc):
	n = t = int(input())
	nums = []
	while n:
		nums.append(n % 3)
		n //= 3
	if 2 not in nums:
		print(t)
	else:
		carry = 0
		for i in range(len(nums)):
			nums[i] += carry
			carry = 0
			if nums[i] >= 2:
				for j in range(i + 1):
					nums[j] = 0
				carry = 1
		if carry:
			nums.append(1)
		ans = 0
		for i in range(len(nums)):
			ans += nums[i] * 3 ** i
		print(ans)


m = int(input())
for e in range(m):
	num = []
	v = int(input())
	d = v
	q = -1
	while q != 0:
		q = d // 3
		r = d % 3
		d = q
		num.append(r)
	num = num[::-1]
	i = 0
	while i < len(num) and num[i] != 2:
		i += 1
	num = [x if p <= i else 0 for (p, x) in enumerate(num)]
	if i >= len(num):
		i -= 1
	num = [0] + num
	i += 1
	while i > 0:
		if num[i] == 2:
			num[i] = 0
			num[i - 1] += 1
		i -= 1
	j = 0
	acc = 0
	for k in num[::-1]:
		acc += k * 3 ** j
		j += 1
	print(acc)


from sys import stdout, stdin
x = list(reversed([3 ** i for i in range(0, 40)]))
for i in stdin:
	q = int(i)
	break
for i in range(q):
	for j in stdin:
		n = int(j)
		break
	l = []
	remain = n
	s = 0
	while remain:
		if s == 1:
			break
		for j in x:
			if j <= remain:
				if len(l) > 0 and l[-1] == j:
					l.append(j)
					while len(l) > 1 and l[-2] == l[-1]:
						k = l[-1] * 3
						del l[-1]
						del l[-1]
						l.append(k)
					s = 1
					break
				else:
					l.append(j)
					remain -= j
					break
	stdout.write(str(sum([j for j in l])) + '\n')


t = int(input())
for m in range(t):
	n = int(input())
	l = []
	p = n
	while n > 0:
		l.append(n % 3)
		n = n // 3
	if max(l) < 2:
		print(p)
	else:
		l.append(0)
		point = len(l) - 1
		while l[point] != 2:
			point -= 1
		for k in range(point, len(l)):
			if l[k] == 2:
				if l[k + 1] == 0:
					target = k + 1
					break
				else:
					l[k] = 0
					l[k + 1] += 1
			elif l[k] == 3:
				l[k] = 0
				l[k] += 1
		for i in range(0, target):
			l[i] = 0
		l[target] = 1
		ans = 0
		for i in range(len(l)):
			ans += l[i] * pow(3, i)
		print(ans)


for _ in range(int(input())):
	x = int(input())
	i = x
	c = 0
	f = []
	fl = 0
	while i > 0:
		k = i % 3
		i = i // 3
		f.append(k)
		if k == 2:
			fl = 1
	f.append(0)
	if fl == 1:
		i = len(f) - 1
		while f[i] != 2:
			i -= 1
		j = i + 1
		while f[j] != 0:
			f[j] = 0
			j += 1
		f[j] = 1
		for i in range(j):
			f[i] = 0
		ans = 0
		for i in range(len(f)):
			ans += 3 ** i * f[i]
	else:
		ans = x
	print(ans)


for _ in range(int(input())):
	N = int(input())
	L = []
	while N:
		L.append(N % 3)
		N = N // 3
	n = len(L)
	carry = 0
	number = 0
	L.append(0)
	for i in range(n + 1):
		if L[i] == 2:
			for j in range(i + 1):
				L[j] = 0
			if L[i + 1] == 2:
				L[i + 1] = 2
			elif L[i + 1] == 0:
				L[i + 1] = 1
			elif L[i + 1] == 1:
				L[i + 1] = 2
	ans = 0
	for i in range(n + 1):
		ans = ans + 3 ** i * L[i]
	print(ans)


import sys
import math
input = sys.stdin.readline
po = list()
po.append(1)
for i in range(40):
	po.append(po[i] * 3)
q = int(input())
for _ in range(q):
	n = int(input())
	vis = [0] * 40
	ans = 0
	for i in range(38, -1, -1):
		if ans + po[i] <= n:
			ans += po[i]
			vis[i] = 1
	if ans == n:
		print(ans)
	else:
		for i in range(0, 40):
			if vis[i] == 1:
				ans -= po[i]
				vis[i] = 0
			else:
				print(ans + po[i])
				break


T = int(input())
while T > 0:
	T -= 1
	n = int(input())
	ss = n
	a = []
	while n > 0:
		a.append(n % 3)
		n = n // 3
	fd = -1
	a.append(0)
	p = len(a)
	for i in range(p - 1, -1, -1):
		if a[i] == 2:
			fd = i
			break
	if fd == -1:
		print(ss)
	else:
		for i in range(fd, p):
			if a[i] == 0:
				a[i] = 1
				for j in range(0, i):
					a[j] = 0
				break
		(ans, k) = (0, 1)
		for i in range(0, p):
			ans += a[i] * k
			k *= 3
		print(ans)


q = int(input())
for cas in range(q):
	n = int(input())
	s = ''
	while n != 0:
		s += str(n % 3)
		n //= 3
	s += '0'
	s = s[::-1]
	if '2' in s:
		pos = len(s) - 1
		for i in range(len(s)):
			if s[i] == '2':
				pos = i
				break
		for i in range(0, pos)[::-1]:
			if s[i] == '0':
				s = s[:i] + '1' + '0' * (len(s) - i - 1)
				break
	print(int(s, 3))


import bisect
t = int(input())
tmp_ans = [0] * 40
for i in range(40):
	tmp_ans[i] = 3 ** i
ruiseki = [0] * 41
for i in range(40):
	ruiseki[i + 1] = ruiseki[i] + tmp_ans[i]
for _ in range(t):
	n = int(input())
	ind = bisect.bisect_left(ruiseki, n)
	ans = ruiseki[ind]
	for i in range(ind)[::-1]:
		if ans - tmp_ans[i] >= n:
			ans -= tmp_ans[i]
	print(ans)


cases = int(input())
for t in range(cases):
	n = int(input())
	out = []
	while n:
		r = n % 3
		out.append(r)
		n //= 3
	lo = len(out)
	pos = -1
	for i in range(lo):
		if out[i] == 2:
			pos = i
	if pos == -1:
		print(sum([pow(3, i) for i in range(lo) if out[i] == 1]))
	else:
		out.append(0)
		for i in range(pos, lo):
			if out[i] == 2:
				out[i] = 0
				out[i + 1] += 1
		print(sum([pow(3, i) for i in range(pos + 1, lo + 1) if out[i] == 1]))


powerThree = [3 ** p for p in range(40)][::-1]
total = sum(powerThree)
for _ in range(int(input())):
	n = int(input())
	ret = total
	for val in powerThree:
		if ret - val >= n:
			ret -= val
	print(ret)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = I()
	rr = []
	for _ in range(t):
		n = I()
		r = 0
		k = 1
		while n > 0:
			if n % 3 == 2:
				r = 0
				n //= 3
				n += 1
			else:
				r += k * (n % 3)
				n //= 3
			k *= 3
		rr.append(r)
	return JA(rr, '\n')
print(main())


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush, heappop, heapify
from itertools import permutations, combinations
from itertools import accumulate as ac
mod = int(1000000000.0) + 7
mod = 998244353
ip = lambda : int(stdin.readline())
inp = lambda : map(int, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()
out = lambda x: stdout.write(str(x) + '\n')
t = ip()
for _ in range(t):
	n = ip()
	store = n
	bit = [0] * 50
	ct = 0
	while n > 0:
		rem = n % 3
		bit[ct] = rem
		ct += 1
		n = n // 3
	ct = 0
	flag = True
	nn = len(bit)
	for i in range(nn):
		if bit[i] == 2:
			flag = False
			last = i
	if flag:
		ans = store
	else:
		for i in range(last + 1, 50):
			if bit[i] == 1:
				bit[i] = 0
			elif bit[i] == 0:
				bit[i] = 1
				break
			else:
				bit[i] = 0
				bit[i + 1] = 1
				break
		for i in range(last + 1):
			bit[i] = 0
		ans = 0
		for i in range(50):
			ans += bit[i] * pow(3, i)
	out(ans)


q = int(input())
pow3 = [0 for _ in range(39)]
sumpow3 = [0 for _ in range(39)]
pow3[0] = 1
for i in range(1, 39):
	pow3[i] = pow3[i - 1] * 3
sumpow3[0] = 1
for i in range(1, 39):
	sumpow3[i] = sumpow3[i - 1] + pow3[i]
for _ in range(q):
	n = int(input())
	ans = 0
	while 1:
		pos = -1
		for i in range(38, -1, -1):
			if n > sumpow3[i]:
				pos = i
				break
		if pow3[pos + 1] >= n:
			ans += pow3[pos + 1]
			break
		n -= pow3[pos + 1]
		ans += pow3[pos + 1]
		if n == 0:
			break
	print(ans)


import sys

def chg3(a):
	ret = []
	while a >= 1:
		ret.append(a % 3)
		a //= 3
	return ret[::-1]

def chg10(a):
	ret = ''
	for i in range(len(a)):
		ret += str(a[i])
	return int(ret, 3)
tcs = int(input())
for _ in range(tcs):
	n = int(sys.stdin.readline().rstrip())
	chg = chg3(n)
	if chg[0] == 2:
		b10 = '1' + '0' * len(chg)
		print(chg10(b10))
		continue
	has0 = -1
	all1 = -1
	has2 = -1
	for i in range(len(chg)):
		if chg[i] == 2:
			has2 = i
			if has0 == -1:
				all1 = i
				break
			else:
				break
		if chg[i] == 0:
			has0 = i
			continue
	if has2 == -1:
		b10 = ''
		for i in range(len(chg)):
			b10 += str(chg[i])
		print(chg10(b10))
		continue
	if all1 != -1:
		b10 = '1' + '0' * len(chg)
		print(chg10(b10))
		continue
	else:
		b10 = ''
		chg[has0] = 1
		for i in range(has0 + 1):
			b10 += str(chg[i])
		for i in range(has0 + 1, len(chg)):
			b10 += '0'
		print(chg10(b10))
		continue


for _ in range(int(input())):
	(n, s, ans) = (int(input()), '', 0)
	k = n
	while k:
		s += str(k % 3)
		k //= 3
	a = s[::-1].find('2')
	if a == -1:
		print(n)
		continue
	a = len(s) - a - 1
	b = s[a:].find('0')
	if b == -1:
		print(3 ** len(s))
		continue
	for i in range(a + b + 1, len(s)):
		ans += int(s[i]) * 3 ** i
	print(ans + 3 ** (b + a))


for _ in range(int(input())):
	n = int(input())
	s = [0] * 1000
	cnt = 0
	while n > 0:
		s[cnt] = n % 3
		cnt += 1
		n //= 3
	flag = False
	pos = -1
	for i in range(cnt + 1):
		if s[i] == 2 and flag == False:
			flag = True
			pos = i
		if flag:
			if s[i] == 0:
				s[i] = 1
				flag = False
			else:
				pos = i
	for i in range(pos + 1):
		s[i] = 0
	ans = 0
	mul3 = 1
	for i in range(cnt + 1):
		ans += mul3 * s[i]
		mul3 *= 3
	print(ans)


def goodNumber(n, memo={}):
	if n in memo:
		return memo[n]
	test = new_n = n
	remainder = count = 0
	while test:
		value = test % 3 + remainder
		if value > 1:
			remainder = 1
			new_n = 0
		else:
			remainder = 0
			if new_n != n and value:
				new_n += 3 ** count
		test //= 3
		count += 1
	if new_n:
		memo[n] = new_n
		return new_n
	else:
		memo[n] = 3 ** count
		return memo[n]
tuple((print(goodNumber(int(input()))) for x in range(int(input()))))


def main():
	Q = int(input())
	for query in range(Q):
		N = int(input())

		def f(x):
			if x // 3:
				return f(x // 3) + str(x % 3)
			return str(x % 3)
		S = '{:0>40}'.format(f(N))
		S = S[::-1]
		ans = []
		carry = 0
		for (i, s) in enumerate(S):
			v = int(s) + carry
			if v == 3:
				v = 0
				carry = 1
			elif v == 2:
				v = 0
				carry = 1
			else:
				carry = 0
			if v:
				ans.append(v * 3 ** i)
		answer = 0
		for a in ans[::-1]:
			answer += a
			if N <= answer:
				break
		print(answer)
main()


li = [3 ** i for i in range(40)]
s = sum(li)
t = int(input())
for _ in range(t):
	n = int(input())
	ans = s
	for i in li[::-1]:
		if ans - i >= n:
			ans -= i
	print(ans)


a = int(input())
for i in range(a):
	x = int(input())
	ans = []
	temp = []
	remp = []
	car = 0
	total = 0
	while x:
		ans.append(x % 3)
		x = x // 3
	for i in range(len(ans) - 1, -1, -1):
		temp.append(ans[i])
		remp.append(ans[i])
	for i in range(len(temp) - 1, -1, -1):
		temp[i] += car
		if temp[i] >= 2:
			car = 1
			temp[i] = 0
		else:
			car = 0
	if car:
		print(pow(3, len(temp)))
	else:
		for i in range(len(temp)):
			if remp[i] == 0 and temp[i] != 0:
				for j in range(i + 1, len(temp)):
					temp[j] = 0
				break
		total = 0
		for i in range(len(temp) - 1, -1, -1):
			if temp[i]:
				total += pow(3, len(temp) - 1 - i)
		print(total)


l = []
for i in range(39):
	l.append(3 ** i)
from bisect import bisect_right
for _ in range(int(input())):
	n = int(input())
	s = sum(l)
	for i in l[::-1]:
		if s - i >= n:
			s -= i
	print(s)


from itertools import combinations
MIN_N = 1
MAX_N = 10 ** 18

def create_good_number():
	nums = []
	val = 1
	index = 0
	while val < MAX_N:
		val = 3 ** index
		nums.append(val)
		index += 1
	new_good_nums = nums
	return new_good_nums

def find_good_number(numbers):

	def find_left_right_pos3(number, list_pos3):
		prev = 0
		next = 0
		threshold = 0
		for (idx, val) in enumerate(list_good_number):
			if val >= number and idx >= 1:
				prev = list_good_number[idx - 1]
				next = val
				break
			elif val >= number and idx == 0:
				prev = 0
				next = val
				break
			else:
				threshold += val
				continue
		return (prev, next, threshold)
	list_good_number = create_good_number()
	for number in numbers:
		(left, right_most, threshold) = find_left_right_pos3(number, list_good_number)
		if right_most == number:
			print(right_most)
			continue
		subtraction = right_most - number
		if left == 0:
			print(1)
			continue
		if right_most == 3:
			print(max(3, number))
			continue
		result = left
		prev_l = left
		prev_r = right_most
		while subtraction >= 0:
			subtraction = number - result
			(left, right, threshold) = find_left_right_pos3(subtraction, list_good_number)
			if left == prev_l and right == prev_r:
				result = right_most
				break
			if result >= number:
				break
			if right == 3:
				if prev_l == right:
					if subtraction >= 2:
						result = right_most
					else:
						result += 1
				elif subtraction >= 2:
					result += 3
				else:
					result += 1
				break
			result += right if prev_l != right and result + right >= number and (subtraction > threshold) else left
			prev_l = left
			prev_r = right
			if left == 0 and result <= number:
				if result + 1 < number:
					result = right_most
				break
		print(result)
query_n = int(input())
cases = [int(input()) for _ in range(query_n)]
find_good_number(cases)


import os
import sys
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		n = int(input())
		(m, b) = (n, [])
		while m:
			b.append(m % 3)
			m //= 3
		if b.count(2) == 0:
			print(n)
		else:
			b.reverse()
			(z, ind) = (b.index(2), -1)
			for i in range(z - 1, -1, -1):
				if not b[i]:
					ind = i
					break
			if ind == -1:
				print(pow(3, len(b)))
			else:
				b[ind] = 1
				for i in range(ind + 1, len(b)):
					b[i] = 0
				print(int(''.join(map(str, b)), 3))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


T = int(input())

def ternary(n):
	if n == 0:
		return 0
	nums = []
	while n:
		r = int(n % 3)
		n = int(n // 3)
		nums.append(int(r))
	return nums
for i in range(T):
	b = ternary(int(input()))
	b.append(0)
	i1 = 0
	i2 = 0
	for j in range(len(b)):
		if b[j] == 2:
			i1 = j
	if i1 != 0 or (i1 == 0 and b[0] == 2):
		for j in range(len(b)):
			if b[j] == 0 and j > i1:
				i2 = j
				break
	if i2 != 0:
		b[i2] = 1
		b[:i2] = [0] * i2
	s = 0
	for j in range(i2, len(b)):
		s = s + pow(3, j) * b[j]
	print(s)


t = int(input())
for _ in range(t):
	n = int(input())
	norig = n
	powers = set()
	for k in range(40, -1, -1):
		if 3 ** k <= n:
			powers.add(k)
			n -= 3 ** k
	if n == 0:
		print(norig)
		continue
	r = ''.join(['1' if i in powers else '0' for i in range(40, -1, -1)])
	x = int(r, 2)
	x += 1
	b = '{0:b}'.format(x)
	x = int(b, 3)
	print(x)


import sys, os
from io import BytesIO, IOBase
import collections, itertools, bisect, heapq, math, string
from decimal import *
BUFSIZE = 8192
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		a = [3 ** p for p in range(40)]
		s = sum(a)
		for x in a[::-1]:
			if s - x >= n:
				s = s - x
		print(s)
main()


q = int(input())
for i in range(q):
	n = int(input())
	m = 0
	i = 0
	while m < n:
		m += 3 ** i
		i += 1
	for j in range(i - 1, -1, -1):
		if m - 3 ** j >= n:
			m -= 3 ** j
	print(m)


q = int(input())
while q:
	q -= 1
	n = int(input())
	i = 0
	while i < 40:
		if 3 ** i > n:
			break
		i += 1
	i -= 1
	ans = pow(3, i + 1)
	sum = 0
	while i >= 0:
		pw = 3 ** i
		if sum + pw >= n:
			ans = min(ans, sum + pw)
		else:
			sum += pw
		i -= 1
	print(ans)


from math import log
q = int(input())
for i in range(q):
	n = int(input())
	l = []
	s = n
	p = 0
	while n > 0:
		k = n % 3
		l.append(k)
		n -= k
		n = n // 3
	t = len(l)
	u = t
	h = 0
	test = 0
	start = 0
	count = l.count(2)
	for i in range(t):
		if l[i] == 2:
			count -= 1
		elif l[i] == 1:
			if start == 1:
				h += 3 ** i
		elif l[i] == 0 and count == 0:
			test = 1
			if start == 0:
				start = 1
				h += 3 ** i
	for i in range(t):
		if l[i] == 2:
			s += 3 ** i
			l[i] = 0
			rest = 1
			for j in range(i + 1, t):
				if l[j] + rest <= 2:
					l[j] += 1
					rest = 0
					break
				else:
					l[j] = 0
	out = min(s, 3 ** t)
	if test == 1:
		out = min(out, h)
	print(out)


import sys
input = sys.stdin.readline
import bisect
from functools import lru_cache
sys.setrecursionlimit(10000)
three_list = [3 ** x for x in range(39)]

@lru_cache(maxsize=None)
def solve(n):
	global three_list
	i = bisect.bisect_right(three_list, n)
	if (three_list[i] - 1) // 2 == n:
		return (three_list[i] - 1) // 2
	elif (three_list[i] - 1) // 2 < n:
		return three_list[i]
	else:
		return three_list[i - 1] + solve(n - three_list[i - 1])

def main():
	q = int(input())
	for _ in range(q):
		N = int(input())
		print(solve(N))
main()


def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x - 1)

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = 0
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = mpos(sum_so_far, current_sum)
	return sum_so_far

def pref(li):
	pref_sum = [0]
	for i in li:
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum

def graph(n, m):
	adj = dict()
	for i in range(1, n + 1):
		adj.setdefault(i, 0)
	for i in range(m):
		(a, b) = map(int, input().split())
		adj[a] += 1
		adj[b] += 1
	return adj
import sys
import threading
from math import *
sys.setrecursionlimit(300000)
threading.stack_size(10 ** 8)
po = int(log(10 ** 18)) + 2
li = []
for i in range(po):
	li.append(3 ** i)
li = li[::-1]
s = sum(li)
for _ in range(int(input())):
	n = int(input())
	ans = s
	for i in range(po):
		if ans - li[i] >= n:
			ans -= li[i]
	print(ans)


q = int(input())
for i in range(q):
	n = int(input())
	prod = 1
	prods = [1]
	sum1 = 0
	a = []
	while prod < n:
		sum1 += prod
		a.append(1)
		prod *= 3
		prods.append(prod)
	if sum1 < n:
		print(prod)
	else:
		for i in range(len(prods) - 1, -1, -1):
			if sum1 - prods[i] >= n:
				sum1 -= prods[i]
		print(sum1)


q = int(input())
for _ in range(q):
	n = int(input())
	s = ''
	while n > 0:
		s = str(n % 3) + s
		n = n // 3
	leng = len(s)
	ind_2 = s.find('2')
	fl = 1
	fl_1 = 1
	if ind_2 == -1:
		fl = 0
		fl_1 = 0
		qqq = s
	while fl:
		ind_1 = s.rfind('1', 0, ind_2)
		if ind_2 - ind_1 > 1 or ind_1 == -1:
			fl = 0
		else:
			ind_2 = ind_1
	if fl_1:
		qqq = s[0:max(ind_2 - 1, 0)] + '1' + '0' * (leng - ind_2)
	print(int(qqq, 3))


q = int(input())
for q1 in range(q):
	n = int(input())
	l_base_3 = []
	while n > 0:
		l_base_3 = [n % 3] + l_base_3
		n = n // 3
	pos_primeiro_2 = 0
	achou_2 = False
	for (i, elem) in enumerate(l_base_3):
		if achou_2:
			l_base_3[i] = 0
		elif elem == 2:
			pos_primeiro_2 = i
			achou_2 = True
	if achou_2:
		l_base_3 = [0] + l_base_3
		i = pos_primeiro_2 + 1
		while i >= 0 and l_base_3[i] == 2:
			l_base_3[i] = 0
			l_base_3[i - 1] += 1
			i -= 1
	num = 0
	l_base_3 = l_base_3[::-1]
	for (i, elem) in enumerate(l_base_3):
		num += elem * 3 ** i
	print(num)


q = int(input())
l = []
from math import log

def converter(number, base):
	figures = [int(i, base) for i in str(number)]
	figures = figures[::-1]
	result = 0
	for i in range(len(figures)):
		result += figures[i] * base ** i
	return result
for i in range(q):
	n = int(input())

	def basecvt(x, b=3):
		e = x // b
		q = x % b
		if n == 0:
			return '0'
		elif e == 0:
			return str(q)
		else:
			return basecvt(e) + str(q)
	st = basecvt(n)
	ans = 0
	if st.replace('1', '').replace('0', '') == '':
		ans = st
	elif st.replace('2', '') == '':
		ans = '1' + '0' * len(st)
	else:
		two = st.find('2')
		p2 = '' + '0' * (len(st) - two)
		st = st[:two]
		if st.replace('1', '') == '':
			p1 = '1' + '0' * len(st)
		else:
			zero = st.rfind('0')
			p1 = st[:zero] + '1' + '0' * len(st[zero + 1:])
		ans = p1 + p2
	l.append(converter(int(ans), 3))
print('\n'.join((str(k) for k in l)))


import sys

def convert(num):
	l = []
	while num != 0:
		a = num % 3
		num = num // 3
		if a != 0:
			l.append(1)
		else:
			l.append(0)
	l.reverse()
	return l

def back(l):
	ans = 0
	for i in range(len(l)):
		ans = ans * 3 + l[i]
	return ans
t = int(sys.stdin.readline())
for _ in range(t):
	n = int(sys.stdin.readline())
	(l, r) = (0, 10 ** 30 + 1)
	ans = 10 ** 40 + 1
	while l <= r:
		mid = (l + r) // 2
		x = convert(mid)
		num = back(x)
		if num < n:
			l = mid + 1
		else:
			ans = min(ans, num)
			r = mid - 1
	print(ans)


def standard(s):
	up = 0
	last = 0
	for (idx, x) in enumerate(s):
		s[idx] += up
		if s[idx] >= 2:
			s[idx] = 0
			up = 1
			last = idx + 1
		else:
			up = 0
	if up == 1:
		s.append(1)
	for i in range(last):
		s[i] = 0

def to_triple(x):
	result = []
	while x >= 1:
		(x, m) = divmod(x, 3)
		result.append(m)
	return result
k = int(input())
for _ in range(k):
	s = to_triple(int(input()))
	standard(s)
	print(int(''.join(reversed([str(x) for x in s])), base=3))


import sys
input = sys.stdin.readline
q = int(input())
for k in range(q):
	n = int(input())
	l = []
	while True:
		l.append(n % 3)
		n //= 3
		if n <= 2:
			l.append(n)
			break
	if 2 not in l:
		ans = 0
		i = 0
		for li in l:
			ans += li * 3 ** i
			i += 1
		print(ans)
		continue
	l = l[::-1]
	for i in range(len(l)):
		if l[i] == 2:
			mark = i
			break
	for i in range(mark - 1, -1, -1):
		if l[i] == 0:
			l[i] = 1
			for j in range(i + 1, len(l)):
				l[j] = 0
			l = l[::-1]
			break
	else:
		l = l[::-1]
		l.append(1)
		for i in range(len(l) - 1):
			l[i] = 0
	ans = 0
	i = 0
	for li in l:
		ans += li * 3 ** i
		i += 1
	print(ans)


import sys
import math
from collections import defaultdict
from itertools import combinations
from itertools import permutations
input = lambda : sys.stdin.readline().rstrip()
read = lambda : map(int, input().split())

def write(*args, sep='\n'):
	for i in args:
		sys.stdout.write('{}'.format(i) + sep)
INF = float('inf')
MOD = int(1000000000.0 + 7)
for _ in range(int(input())):
	n = int(input())
	idx = -1
	for i in range(40):
		if (3 ** (i + 1) - 1) // 2 >= n:
			idx = i
			break
	ans = (3 ** (idx + 1) - 1) // 2
	for i in reversed(range(idx)):
		if ans - 3 ** i >= n:
			ans -= 3 ** i
	print(ans)


def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))

def toDec(a, base):
	ans = 0
	inc = 1
	while a:
		digit = inc * (a % 10)
		ans += digit
		a //= 10
		inc *= base
	return ans
q = int(input())
for i in range(q):
	n = int(input())
	base3 = ternary(n)
	base3 = '0' + base3
	index = base3.find('2')
	copia = index
	lista = list(base3)
	for j in range(len(lista)):
		lista[j] = int(lista[j])
	if index != -1:
		while index > 0:
			if lista[index] == 2:
				lista[index] = 0
				lista[index - 1] += 1
			index -= 1
		for k in range(copia, len(lista)):
			if lista[k] != 0:
				lista[k] = 0
		for k in range(len(lista)):
			lista[k] = str(lista[k])
		pronto = ''.join(lista)
		print(toDec(int(pronto), 3))
	else:
		print(n)


def toDigits(n, b):
	digits = []
	while n:
		digits.append(n % b)
		n //= b
	return digits

def fromDigits(digits, b):
	n = 0
	for i in range(len(digits) - 1, -1, -1):
		d = digits[i]
		n = b * n + d
	return n
q = int(input())
for _ in range(q):
	n = int(input())
	digits = toDigits(n, 3)
	digits.append(0)
	m = len(digits)
	broke = False
	for i in range(m - 1, -1, -1):
		if digits[i] == 2:
			mostSignificant2 = i
			broke = True
			break
	if broke == False:
		print(n)
	else:
		carry = 2
		latestSetDigit = 0
		for i in range(mostSignificant2 + 1, m):
			if carry == 2:
				latestSetDigit = i
				digits[i] += 1
				if digits[i] == 1:
					carry = 0
		for i in range(latestSetDigit):
			digits[i] = 0
		ans = fromDigits(digits, 3)
		print(ans)


for q in range(int(input())):
	n = int(input())
	low = 1
	high = 10 ** 18
	ans = 10 ** 20
	while low <= high:
		mid = (high + low) // 2
		binary = bin(mid)[2:]
		resulting_value = 0
		for i in range(-1, -len(binary), -1):
			resulting_value += pow(3, abs(i + 1)) * int(binary[i])
		if resulting_value >= n:
			ans = min(ans, resulting_value)
			high = mid - 1
		else:
			low = mid + 1
	print(ans)


import sys, re, math
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from heapq import heappush, heappop, heapify, nlargest, nsmallest

def STR():
	return list(input())

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST():
	return list(map(int, input().split()))

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def sortListWithIndex(listOfTuples, idx):
	return sorted(listOfTuples, key=lambda x: x[idx])

def sortDictWithVal(passedDic):
	temp = sorted(passedDic.items(), key=lambda kv: (kv[1], kv[0]))[::-1]
	toret = {}
	for tup in temp:
		toret[tup[0]] = tup[1]
	return toret

def sortDictWithKey(passedDic):
	return dict(OrderedDict(sorted(passedDic.items())))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))
t = INT()
while t != 0:
	n = INT()
	converted = ternary(n)
	if '2' not in converted:
		print(n)
	else:
		if '0' not in converted:
			l = ['0'] * len(converted)
			st = ''.join(l)
			st = '1' + st
		else:
			twoIdx = converted.find('2')
			zeroIdx = twoIdx + 1
			for i in range(twoIdx, -1, -1):
				if converted[i] == '0':
					zeroIdx = i
					break
			if twoIdx < zeroIdx:
				l = ['0'] * len(converted)
				st = ''.join(l)
				st = '1' + st
			else:
				foo = converted[:zeroIdx]
				foo += '1'
				l = '0' * (len(converted) - len(foo))
				tot = foo + l
				st = ''.join(tot)
		print(int(st, 3))
	t -= 1


from sys import stdin
from sys import setrecursionlimit as SRL
SRL(10 ** 7)
rd = stdin.readline
rrd = lambda : map(int, rd().strip().split())
q = int(rd())
cnt = [0] * 55
for i in range(40):
	if i:
		cnt[i] = cnt[i - 1] + 3 ** i
	else:
		cnt[i] = 1
while q:
	n = int(rd())
	pos = 0
	for i in range(55):
		if cnt[i] >= n:
			pos = i
			break
	tot = 0
	for i in range(pos + 1)[::-1]:
		if i and tot + cnt[i - 1] >= n:
			continue
		tot += 3 ** i
		if tot >= n:
			break
	print(tot)
	q -= 1


n = int(input())
for i in range(n):
	a = int(input())
	new_a = a
	b = ''
	f = 0
	while new_a > 0:
		b = str(new_a % 3) + b
		new_a = new_a // 3
	for i in b:
		if int(i) == 2:
			f = 1
	if f == 1:
		ch = b[:b.find('2')]
		m = 0
		for j in range(len(ch)):
			m += int(ch[j]) * 2 ** (len(ch) - j - 1)
		m += 1
		number = m
		c = ''
		while number > 0:
			c = str(number % 2) + c
			number = number // 2
		itog = '0'
		for i in range(len(b) - b.find('2') - 1):
			itog += '0'
		itogg = c + itog
		numberkon = 0
		for j in range(0, len(itogg)):
			numberkon += int(itogg[j]) * 3 ** (len(itogg) - j - 1)
		print(numberkon)
	else:
		print(a)


def to_string(n):
	res = ''
	while n:
		res = str(n % 3) + res
		n //= 3
	res = list(res)
	return res

def to_int(s):
	res = 0
	for i in range(len(s)):
		res *= 3
		res += int(s[i])
	return res
q = int(input())
for _ in range(q):
	n = int(input())
	s = to_string(n)
	good = False
	while not good:
		cnt = 0
		idx = 10000
		for i in range(len(s)):
			if s[i] == '2':
				cnt += 1
				idx = min(idx, i)
		if cnt == 0:
			good = True
		if not good:
			for i in range(idx + 1, len(s)):
				s[i] = '0'
			n = to_int(s)
			n += 3 ** (len(s) - idx - 1)
			s = to_string(n)
	print(n)


import math as ma
q = int(input())
for w in range(q):
	n = int(input())
	m = n
	i = ma.ceil(ma.log(n, 3))
	j = i - 1
	k = 0
	r = n
	while m >= 0 and j >= 0:
		if m >= 3 ** j:
			m = m - 3 ** j
		else:
			k = j
			r = n - m
		j = j - 1
	if m == 0:
		print(n)
	elif k > 0:
		print(r + 3 ** k)
	else:
		print(3 ** i)


t = int(input())
for case_num in range(t):
	n0 = int(input())
	n = n0
	a = []
	while n > 0:
		a.append(n % 3)
		n //= 3
	i = 0
	while i < len(a) and a[i] != 2:
		i += 1
	if i == len(a):
		print(n0)
	else:
		i = len(a) - 1
		while a[i] != 2:
			i -= 1
		for j in range(i):
			a[j] = 0
		while i < len(a) and a[i] == 2:
			if i == len(a) - 1:
				a.append(0)
			a[i] = 0
			a[i + 1] += 1
			i += 1
		ans = 0
		curr = 1
		for j in a:
			ans += curr * j
			curr *= 3
		print(ans)