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

Source: codeforces | Difficulty: EASY
Tags: Complete search

Implementation

Greedy algorithms


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)


t = int(input())
for i in range(t):
	n = int(input())
	while True:
		ok = True
		curr = n
		while curr > 0:
			if ok and curr % 3 == 2:
				ok = False
			curr = curr // 3
		if ok:
			break
		n += 1
	print(n)


import sys, math, bisect

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

def main():
	q = int(input())
	t = []
	for k in range(10):
		t.append(3 ** k)
	s = []
	for k in range(2 ** 10):
		x = 0
		for b in range(10):
			if k >> b & 1 == 1:
				x += t[b]
		s.append(x)
	for _ in range(q):
		n = int(input())
		print(s[bisect.bisect_left(s, n)])
main()


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

	def base_3(n):
		ternary = ''
		while n > 0:
			ternary += str(n % 3)
			if '2' in ternary:
				break
			n = n // 3
		return ternary[-1::-1]
	while '2' in base_3(n):
		n = temp + 1
		temp = temp + 1
	print(n)


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(10)]
s = sum(arr)
t = int(input())
for _ in range(t):
	n = int(input())
	m = s
	for i in arr[::-1]:
		if m - i >= n:
			m -= i
	print(m)


T = [0, 1, 3, 4, 9, 10, 12, 13, 27, 28, 30, 31, 36, 37, 39, 40, 81, 82, 84, 85, 90, 91, 93, 94, 108, 109, 111, 112, 117, 118, 120, 121, 243, 244, 246, 247, 252, 253, 255, 256, 270, 271, 273, 274, 279, 280, 282, 283, 324, 325, 327, 328, 333, 334, 336, 337, 351, 352, 354, 355, 360, 361, 363, 364, 729, 730, 732, 733, 738, 739, 741, 742, 756, 757, 759, 760, 765, 766, 768, 769, 810, 811, 813, 814, 819, 820, 822, 823, 837, 838, 840, 841, 846, 847, 849, 850, 972, 973, 975, 976, 981, 982, 984, 985, 999, 1000, 1002, 1003, 1008, 1009, 1011, 1012, 1053, 1054, 1056, 1057, 1062, 1063, 1065, 1066, 1080, 1081, 1083, 1084, 1089, 1090, 1092, 1093, 2187, 2188, 2190, 2191, 2196, 2197, 2199, 2200, 2214, 2215, 2217, 2218, 2223, 2224, 2226, 2227, 2268, 2269, 2271, 2272, 2277, 2278, 2280, 2281, 2295, 2296, 2298, 2299, 2304, 2305, 2307, 2308, 2430, 2431, 2433, 2434, 2439, 2440, 2442, 2443, 2457, 2458, 2460, 2461, 2466, 2467, 2469, 2470, 2511, 2512, 2514, 2515, 2520, 2521, 2523, 2524, 2538, 2539, 2541, 2542, 2547, 2548, 2550, 2551, 2916, 2917, 2919, 2920, 2925, 2926, 2928, 2929, 2943, 2944, 2946, 2947, 2952, 2953, 2955, 2956, 2997, 2998, 3000, 3001, 3006, 3007, 3009, 3010, 3024, 3025, 3027, 3028, 3033, 3034, 3036, 3037, 3159, 3160, 3162, 3163, 3168, 3169, 3171, 3172, 3186, 3187, 3189, 3190, 3195, 3196, 3198, 3199, 3240, 3241, 3243, 3244, 3249, 3250, 3252, 3253, 3267, 3268, 3270, 3271, 3276, 3277, 3279, 3280, 6561, 6562, 6564, 6565, 6570, 6571, 6573, 6574, 6588, 6589, 6591, 6592, 6597, 6598, 6600, 6601, 6642, 6643, 6645, 6646, 6651, 6652, 6654, 6655, 6669, 6670, 6672, 6673, 6678, 6679, 6681, 6682, 6804, 6805, 6807, 6808, 6813, 6814, 6816, 6817, 6831, 6832, 6834, 6835, 6840, 6841, 6843, 6844, 6885, 6886, 6888, 6889, 6894, 6895, 6897, 6898, 6912, 6913, 6915, 6916, 6921, 6922, 6924, 6925, 7290, 7291, 7293, 7294, 7299, 7300, 7302, 7303, 7317, 7318, 7320, 7321, 7326, 7327, 7329, 7330, 7371, 7372, 7374, 7375, 7380, 7381, 7383, 7384, 7398, 7399, 7401, 7402, 7407, 7408, 7410, 7411, 7533, 7534, 7536, 7537, 7542, 7543, 7545, 7546, 7560, 7561, 7563, 7564, 7569, 7570, 7572, 7573, 7614, 7615, 7617, 7618, 7623, 7624, 7626, 7627, 7641, 7642, 7644, 7645, 7650, 7651, 7653, 7654, 8748, 8749, 8751, 8752, 8757, 8758, 8760, 8761, 8775, 8776, 8778, 8779, 8784, 8785, 8787, 8788, 8829, 8830, 8832, 8833, 8838, 8839, 8841, 8842, 8856, 8857, 8859, 8860, 8865, 8866, 8868, 8869, 8991, 8992, 8994, 8995, 9000, 9001, 9003, 9004, 9018, 9019, 9021, 9022, 9027, 9028, 9030, 9031, 9072, 9073, 9075, 9076, 9081, 9082, 9084, 9085, 9099, 9100, 9102, 9103, 9108, 9109, 9111, 9112, 9477, 9478, 9480, 9481, 9486, 9487, 9489, 9490, 9504, 9505, 9507, 9508, 9513, 9514, 9516, 9517, 9558, 9559, 9561, 9562, 9567, 9568, 9570, 9571, 9585, 9586, 9588, 9589, 9594, 9595, 9597, 9598, 9720, 9721, 9723, 9724, 9729, 9730, 9732, 9733, 9747, 9748, 9750, 9751, 9756, 9757, 9759, 9760, 9801, 9802, 9804, 9805, 9810, 9811, 9813, 9814, 9828, 9829, 9831, 9832, 9837, 9838, 9840, 9841, 19683, 19684, 19686, 19687, 19692, 19693, 19695, 19696, 19710, 19711, 19713, 19714, 19719, 19720, 19722, 19723, 19764, 19765, 19767, 19768, 19773, 19774, 19776, 19777, 19791, 19792, 19794, 19795, 19800, 19801, 19803, 19804, 19926, 19927, 19929, 19930, 19935, 19936, 19938, 19939, 19953, 19954, 19956, 19957, 19962, 19963, 19965, 19966, 20007, 20008, 20010, 20011, 20016, 20017, 20019, 20020, 20034, 20035, 20037, 20038, 20043, 20044, 20046, 20047, 20412, 20413, 20415, 20416, 20421, 20422, 20424, 20425, 20439, 20440, 20442, 20443, 20448, 20449, 20451, 20452, 20493, 20494, 20496, 20497, 20502, 20503, 20505, 20506, 20520, 20521, 20523, 20524, 20529, 20530, 20532, 20533, 20655, 20656, 20658, 20659, 20664, 20665, 20667, 20668, 20682, 20683, 20685, 20686, 20691, 20692, 20694, 20695, 20736, 20737, 20739, 20740, 20745, 20746, 20748, 20749, 20763, 20764, 20766, 20767, 20772, 20773, 20775, 20776, 21870, 21871, 21873, 21874, 21879, 21880, 21882, 21883, 21897, 21898, 21900, 21901, 21906, 21907, 21909, 21910, 21951, 21952, 21954, 21955, 21960, 21961, 21963, 21964, 21978, 21979, 21981, 21982, 21987, 21988, 21990, 21991, 22113, 22114, 22116, 22117, 22122, 22123, 22125, 22126, 22140, 22141, 22143, 22144, 22149, 22150, 22152, 22153, 22194, 22195, 22197, 22198, 22203, 22204, 22206, 22207, 22221, 22222, 22224, 22225, 22230, 22231, 22233, 22234, 22599, 22600, 22602, 22603, 22608, 22609, 22611, 22612, 22626, 22627, 22629, 22630, 22635, 22636, 22638, 22639, 22680, 22681, 22683, 22684, 22689, 22690, 22692, 22693, 22707, 22708, 22710, 22711, 22716, 22717, 22719, 22720, 22842, 22843, 22845, 22846, 22851, 22852, 22854, 22855, 22869, 22870, 22872, 22873, 22878, 22879, 22881, 22882, 22923, 22924, 22926, 22927, 22932, 22933, 22935, 22936, 22950, 22951, 22953, 22954, 22959, 22960, 22962, 22963, 26244, 26245, 26247, 26248, 26253, 26254, 26256, 26257, 26271, 26272, 26274, 26275, 26280, 26281, 26283, 26284, 26325, 26326, 26328, 26329, 26334, 26335, 26337, 26338, 26352, 26353, 26355, 26356, 26361, 26362, 26364, 26365, 26487, 26488, 26490, 26491, 26496, 26497, 26499, 26500, 26514, 26515, 26517, 26518, 26523, 26524, 26526, 26527, 26568, 26569, 26571, 26572, 26577, 26578, 26580, 26581, 26595, 26596, 26598, 26599, 26604, 26605, 26607, 26608, 26973, 26974, 26976, 26977, 26982, 26983, 26985, 26986, 27000, 27001, 27003, 27004, 27009, 27010, 27012, 27013, 27054, 27055, 27057, 27058, 27063, 27064, 27066, 27067, 27081, 27082, 27084, 27085, 27090, 27091, 27093, 27094, 27216, 27217, 27219, 27220, 27225, 27226, 27228, 27229, 27243, 27244, 27246, 27247, 27252, 27253, 27255, 27256, 27297, 27298, 27300, 27301, 27306, 27307, 27309, 27310, 27324, 27325, 27327, 27328, 27333, 27334, 27336, 27337, 28431, 28432, 28434, 28435, 28440, 28441, 28443, 28444, 28458, 28459, 28461, 28462, 28467, 28468, 28470, 28471, 28512, 28513, 28515, 28516, 28521, 28522, 28524, 28525, 28539, 28540, 28542, 28543, 28548, 28549, 28551, 28552, 28674, 28675, 28677, 28678, 28683, 28684, 28686, 28687, 28701, 28702, 28704, 28705, 28710, 28711, 28713, 28714, 28755, 28756, 28758, 28759, 28764, 28765, 28767, 28768, 28782, 28783, 28785, 28786, 28791, 28792, 28794, 28795, 29160, 29161, 29163, 29164, 29169, 29170, 29172, 29173, 29187, 29188, 29190, 29191, 29196, 29197, 29199, 29200, 29241, 29242, 29244, 29245, 29250, 29251, 29253, 29254, 29268, 29269, 29271, 29272, 29277, 29278, 29280, 29281, 29403, 29404, 29406, 29407, 29412, 29413, 29415, 29416, 29430, 29431, 29433, 29434, 29439, 29440, 29442, 29443, 29484, 29485, 29487, 29488, 29493, 29494, 29496, 29497, 29511, 29512, 29514, 29515, 29520, 29521, 29523, 29524, 59049, 59050, 59052, 59053, 59058, 59059, 59061, 59062, 59076, 59077, 59079, 59080, 59085, 59086, 59088, 59089, 59130, 59131, 59133, 59134, 59139, 59140, 59142, 59143, 59157, 59158, 59160, 59161, 59166, 59167, 59169, 59170, 59292, 59293, 59295, 59296, 59301, 59302, 59304, 59305, 59319, 59320, 59322, 59323, 59328, 59329, 59331, 59332, 59373, 59374, 59376, 59377, 59382, 59383, 59385, 59386, 59400, 59401, 59403, 59404, 59409, 59410, 59412, 59413, 59778, 59779, 59781, 59782, 59787, 59788, 59790, 59791, 59805, 59806, 59808, 59809, 59814, 59815, 59817, 59818, 59859, 59860, 59862, 59863, 59868, 59869, 59871, 59872, 59886, 59887, 59889, 59890, 59895, 59896, 59898, 59899, 60021, 60022, 60024, 60025, 60030, 60031, 60033, 60034, 60048, 60049, 60051, 60052, 60057, 60058, 60060, 60061, 60102, 60103, 60105, 60106, 60111, 60112, 60114, 60115, 60129, 60130, 60132, 60133, 60138, 60139, 60141, 60142, 61236, 61237, 61239, 61240, 61245, 61246, 61248, 61249, 61263, 61264, 61266, 61267, 61272, 61273, 61275, 61276, 61317, 61318, 61320, 61321, 61326, 61327, 61329, 61330, 61344, 61345, 61347, 61348, 61353, 61354, 61356, 61357, 61479, 61480, 61482, 61483, 61488, 61489, 61491, 61492, 61506, 61507, 61509, 61510, 61515, 61516, 61518, 61519, 61560, 61561, 61563, 61564, 61569, 61570, 61572, 61573, 61587, 61588, 61590, 61591, 61596, 61597, 61599, 61600, 61965, 61966, 61968, 61969, 61974, 61975, 61977, 61978, 61992, 61993, 61995, 61996, 62001, 62002, 62004, 62005, 62046, 62047, 62049, 62050, 62055, 62056, 62058, 62059, 62073, 62074, 62076, 62077, 62082, 62083, 62085, 62086, 62208, 62209, 62211, 62212, 62217, 62218, 62220, 62221, 62235, 62236, 62238, 62239, 62244, 62245, 62247, 62248, 62289, 62290, 62292, 62293, 62298, 62299, 62301, 62302, 62316, 62317, 62319, 62320, 62325, 62326, 62328, 62329, 65610, 65611, 65613, 65614, 65619, 65620, 65622, 65623, 65637, 65638, 65640, 65641, 65646, 65647, 65649, 65650, 65691, 65692, 65694, 65695, 65700, 65701, 65703, 65704, 65718, 65719, 65721, 65722, 65727, 65728, 65730, 65731, 65853, 65854, 65856, 65857, 65862, 65863, 65865, 65866, 65880, 65881, 65883, 65884, 65889, 65890, 65892, 65893, 65934, 65935, 65937, 65938, 65943, 65944, 65946, 65947, 65961, 65962, 65964, 65965, 65970, 65971, 65973, 65974, 66339, 66340, 66342, 66343, 66348, 66349, 66351, 66352, 66366, 66367, 66369, 66370, 66375, 66376, 66378, 66379, 66420, 66421, 66423, 66424, 66429, 66430, 66432, 66433, 66447, 66448, 66450, 66451, 66456, 66457, 66459, 66460, 66582, 66583, 66585, 66586, 66591, 66592, 66594, 66595, 66609, 66610, 66612, 66613, 66618, 66619, 66621, 66622, 66663, 66664, 66666, 66667, 66672, 66673, 66675, 66676, 66690, 66691, 66693, 66694, 66699, 66700, 66702, 66703, 67797, 67798, 67800, 67801, 67806, 67807, 67809, 67810, 67824, 67825, 67827, 67828, 67833, 67834, 67836, 67837, 67878, 67879, 67881, 67882, 67887, 67888, 67890, 67891, 67905, 67906, 67908, 67909, 67914, 67915, 67917, 67918, 68040, 68041, 68043, 68044, 68049, 68050, 68052, 68053, 68067, 68068, 68070, 68071, 68076, 68077, 68079, 68080, 68121, 68122, 68124, 68125, 68130, 68131, 68133, 68134, 68148, 68149, 68151, 68152, 68157, 68158, 68160, 68161, 68526, 68527, 68529, 68530, 68535, 68536, 68538, 68539, 68553, 68554, 68556, 68557, 68562, 68563, 68565, 68566, 68607, 68608, 68610, 68611, 68616, 68617, 68619, 68620, 68634, 68635, 68637, 68638, 68643, 68644, 68646, 68647, 68769, 68770, 68772, 68773, 68778, 68779, 68781, 68782, 68796, 68797, 68799, 68800, 68805, 68806, 68808, 68809, 68850, 68851, 68853, 68854, 68859, 68860, 68862, 68863, 68877, 68878, 68880, 68881, 68886, 68887, 68889, 68890, 78732, 78733, 78735, 78736, 78741, 78742, 78744, 78745, 78759, 78760, 78762, 78763, 78768, 78769, 78771, 78772, 78813, 78814, 78816, 78817, 78822, 78823, 78825, 78826, 78840, 78841, 78843, 78844, 78849, 78850, 78852, 78853, 78975, 78976, 78978, 78979, 78984, 78985, 78987, 78988, 79002, 79003, 79005, 79006, 79011, 79012, 79014, 79015, 79056, 79057, 79059, 79060, 79065, 79066, 79068, 79069, 79083, 79084, 79086, 79087, 79092, 79093, 79095, 79096, 79461, 79462, 79464, 79465, 79470, 79471, 79473, 79474, 79488, 79489, 79491, 79492, 79497, 79498, 79500, 79501, 79542, 79543, 79545, 79546, 79551, 79552, 79554, 79555, 79569, 79570, 79572, 79573, 79578, 79579, 79581, 79582, 79704, 79705, 79707, 79708, 79713, 79714, 79716, 79717, 79731, 79732, 79734, 79735, 79740, 79741, 79743, 79744, 79785, 79786, 79788, 79789, 79794, 79795, 79797, 79798, 79812, 79813, 79815, 79816, 79821, 79822, 79824, 79825, 80919, 80920, 80922, 80923, 80928, 80929, 80931, 80932, 80946, 80947, 80949, 80950, 80955, 80956, 80958, 80959, 81000, 81001, 81003, 81004, 81009, 81010, 81012, 81013, 81027, 81028, 81030, 81031, 81036, 81037, 81039, 81040, 81162, 81163, 81165, 81166, 81171, 81172, 81174, 81175, 81189, 81190, 81192, 81193, 81198, 81199, 81201, 81202, 81243, 81244, 81246, 81247, 81252, 81253, 81255, 81256, 81270, 81271, 81273, 81274, 81279, 81280, 81282, 81283, 81648, 81649, 81651, 81652, 81657, 81658, 81660, 81661, 81675, 81676, 81678, 81679, 81684, 81685, 81687, 81688, 81729, 81730, 81732, 81733, 81738, 81739, 81741, 81742, 81756, 81757, 81759, 81760, 81765, 81766, 81768, 81769, 81891, 81892, 81894, 81895, 81900, 81901, 81903, 81904, 81918, 81919, 81921, 81922, 81927, 81928, 81930, 81931, 81972, 81973, 81975, 81976, 81981, 81982, 81984, 81985, 81999, 82000, 82002, 82003, 82008, 82009, 82011, 82012, 85293, 85294, 85296, 85297, 85302, 85303, 85305, 85306, 85320, 85321, 85323, 85324, 85329, 85330, 85332, 85333, 85374, 85375, 85377, 85378, 85383, 85384, 85386, 85387, 85401, 85402, 85404, 85405, 85410, 85411, 85413, 85414, 85536, 85537, 85539, 85540, 85545, 85546, 85548, 85549, 85563, 85564, 85566, 85567, 85572, 85573, 85575, 85576, 85617, 85618, 85620, 85621, 85626, 85627, 85629, 85630, 85644, 85645, 85647, 85648, 85653, 85654, 85656, 85657, 86022, 86023, 86025, 86026, 86031, 86032, 86034, 86035, 86049, 86050, 86052, 86053, 86058, 86059, 86061, 86062, 86103, 86104, 86106, 86107, 86112, 86113, 86115, 86116, 86130, 86131, 86133, 86134, 86139, 86140, 86142, 86143, 86265, 86266, 86268, 86269, 86274, 86275, 86277, 86278, 86292, 86293, 86295, 86296, 86301, 86302, 86304, 86305, 86346, 86347, 86349, 86350, 86355, 86356, 86358, 86359, 86373, 86374, 86376, 86377, 86382, 86383, 86385, 86386, 87480, 87481, 87483, 87484, 87489, 87490, 87492, 87493, 87507, 87508, 87510, 87511, 87516, 87517, 87519, 87520, 87561, 87562, 87564, 87565, 87570, 87571, 87573, 87574, 87588, 87589, 87591, 87592, 87597, 87598, 87600, 87601, 87723, 87724, 87726, 87727, 87732, 87733, 87735, 87736, 87750, 87751, 87753, 87754, 87759, 87760, 87762, 87763, 87804, 87805, 87807, 87808, 87813, 87814, 87816, 87817, 87831, 87832, 87834, 87835, 87840, 87841, 87843, 87844, 88209, 88210, 88212, 88213, 88218, 88219, 88221, 88222, 88236, 88237, 88239, 88240, 88245, 88246, 88248, 88249, 88290, 88291, 88293, 88294, 88299, 88300, 88302, 88303, 88317, 88318, 88320, 88321, 88326, 88327, 88329, 88330, 88452, 88453, 88455, 88456, 88461, 88462, 88464, 88465, 88479, 88480, 88482, 88483, 88488, 88489, 88491, 88492, 88533, 88534, 88536, 88537, 88542, 88543, 88545, 88546, 88560, 88561, 88563, 88564, 88569, 88570, 88572, 88573]
from bisect import bisect_left
(Q, *A) = map(int, open(0).read().split())
for n in A:
	print(T[bisect_left(T, n)])


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 binary_search(data, val):
	high_index = len(data) - 1
	low_index = 0
	while high_index > low_index:
		index = (high_index + low_index) // 2
		sub = data[index]
		if data[low_index] == val:
			return [low_index, low_index]
		elif sub == val:
			return [index, index]
		elif data[high_index] == val:
			return [high_index, high_index]
		elif sub > val:
			if high_index == index:
				return sorted([high_index, low_index])
			high_index = index
		else:
			if low_index == index:
				return sorted([high_index, low_index])
			low_index = index
	return sorted([high_index, low_index])
n = 10 ** 6
i = 0
l = []
r = set()
while 3 ** i <= n:
	l.append(3 ** i)
	i += 1
r = [set()]
for i in range(len(l)):
	for j in range(len(r)):
		z = r[j].copy()
		z.add(l[i])
		r.append(z)
li = [0] * len(r)
for i in range(1, len(r)):
	li[i] = sum(r[i])
for i in range(int(input())):
	a = binary_search(li, int(input()))
	print(li[a[1]])


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)


tar = []
for i in range(10):
	tmp = 3 ** i
	tar.append(tmp)
	tmp2 = tar.copy()
	for t in tmp2:
		if t != tmp:
			tar.append(t + tmp)
from bisect import *
Q = int(input())
for q in range(Q):
	N = int(input())
	idx = bisect_left(tar, N)
	print(tar[idx])


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)


def dectoter(n):
	ter = []
	while True:
		if n == 0:
			break
		else:
			ter.append(n % 3)
		n //= 3
	return ter
test = int(input())
for i in range(test):
	n = int(input())
	ter = []
	temp = n
	j = n
	while True:
		flag = 0
		ter = dectoter(j)
		for i in ter:
			if i == 2:
				flag = 1
				break
		if flag == 1:
			j += 1
		else:
			break
	print(j)


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)


import math
numbers = []
i = 0
while 3 ** i < 10 ** 5:
	numbers.append(3 ** i)
	i += 1
numbers.append(3 ** i)

def solve(n):
	if n in numbers:
		return n
	p = int(math.log(n, 3) // 1)
	if sum(numbers[:p + 1]) < n:
		return numbers[p + 1]
	elif sum(numbers[:p + 1]) == n:
		return n
	else:
		return 3 ** p + solve(n - 3 ** p)
for _ in range(int(input())):
	n = int(input())
	print(solve(n))


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))


import sys
input = sys.stdin.readline
q = int(input())
for i in range(q):
	n = int(input())
	num = n
	st = ''
	while num > 2:
		val = num % 3
		st = str(val) + st
		num = int(num / 3)
	st = str(num) + st
	flag = 0
	for j in st:
		if j == '2':
			flag = 1
			break
	if flag == 0:
		print(n)
	else:
		ind = -1
		a = []
		for j in range(len(st)):
			if st[j] == '2':
				ind = j
				a.append('0')
				for k in range(ind + 1, len(st)):
					a.append('0')
				break
			else:
				a.append(st[j])
		f = 0
		for j in range(ind - 1, -1, -1):
			if a[j] == '0':
				a[j] = '1'
				f = 1
				break
			else:
				a[j] = '0'
		if f == 0:
			print(pow(3, len(st)))
		else:
			s = 0
			for j in range(len(a)):
				if a[j] == '1':
					s += pow(3, len(a) - j - 1)
			print(s)


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)


arr = [1]
v = 1
t = 1
while t < pow(10, 4):
	t = pow(3, v)
	arr.append(t)
	v += 1
s = sum(arr)
arr.sort(reverse=True)
for _ in range(int(input())):
	n = int(input())
	sc = s
	for i in arr:
		if sc - i >= n:
			sc -= i
	print(sc)


import math
from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	p = n
	while True:
		p = n
		ok = True
		while p > 0 and ok:
			if ok and p % 3 == 2:
				ok = False
			p //= 3
		if ok:
			print(n)
			break
		else:
			n += 1


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)


from math import log
li = []
for i in range(11):
	li.append(3 ** i)
for _ in range(int(input())):
	sum1 = sum(li)
	x = int(input())
	for i in li[::-1]:
		if sum1 - i >= x:
			sum1 -= i
	print(sum1)


memo = [False] * 30000
for i in range(pow(2, 10)):
	bitmask = i
	ans = 0
	curr_pot = 0
	for j in range(10):
		ans += pow(3, curr_pot) * (bitmask % 2)
		curr_pot += 1
		bitmask = bitmask // 2
	memo[ans] = True
t = int(input())
for i in range(t):
	n = int(input())
	while not memo[n]:
		n += 1
	print(n)


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)


import sys
from collections import deque
readline = sys.stdin.readline
q = int(readline())

def Tmp(n):
	p3 = [True for _ in range(20)]
	for i in range(20):
		t = 0
		for j in range(20):
			if p3[j]:
				t += pow(3, 19 - j)
		p3[i] = False
		if n > t:
			p3[i - 1] = True
		elif n == t:
			return t
	t = 0
	for j in range(20):
		if p3[j]:
			t += pow(3, 19 - j)
	return t
for _ in range(q):
	n = int(readline())
	print(Tmp(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))


import sys, bisect
sys.setrecursionlimit(1500)
(ex, coins) = ([], [])

def make_coin(c, n):
	if n < 10:
		make_coin(c + ex[n], n + 1)
		make_coin(c, n + 1)
		coins.append(c + ex[n])
ex.append(1)
i = 1
while i <= 9:
	ex.append(ex[len(ex) - 1] * 3)
	i += 1
make_coin(0, 0)
coins.sort()
q = int(input())
for case in range(q):
	N = int(input())
	pos = bisect.bisect(coins, N)
	if pos != len(coins) + 1 and coins[pos - 1] == N:
		pos -= 1
	print(coins[pos])


def ternary(num):
	if num == 0:
		return True
	f = True
	while num != 0:
		(num, r) = divmod(num, 3)
		if r == 2:
			f = False
			break
	if f == True:
		return True
	return False
k = []
for i in range(1, 2 * 10 ** 4 + 1):
	if ternary(i) == True:
		k.append(i)
for qq in range(int(input())):
	n = int(input())
	if ternary(n) == True:
		print(n)
	else:
		for i in k:
			if i > n:
				print(i)
				break


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)


import sys
sys.setrecursionlimit(10 ** 7)
from collections import deque
import math
pow3 = [1]
aux = 1
for i in range(9):
	aux *= 3
	pow3.append(aux)
a = []
for op in range(1 << 10):
	elem = 0
	for i in range(len(pow3)):
		if op >> i & 1:
			elem += pow3[i]
	a.append(elem)
t = int(input())
for _ in range(t):
	n = int(input())
	(lo, hi) = (0, len(a) - 1)
	while hi - lo > 1:
		mi = lo + (hi - lo) // 2
		if n > a[mi]:
			lo = mi
		else:
			hi = mi
	print(a[hi])


t = int(input())

def isGood(n):
	while n:
		(n, r) = divmod(n, 3)
		if r == 2:
			return False
	return True

def solve():
	n = int(input())
	ans = n
	while not isGood(ans):
		ans += 1
	print(ans)
for _ in range(t):
	solve()


q = int(input())
for u in range(q):
	n = int(input())
	k = n
	i = n
	while True:
		s = 0
		while n > 0:
			a = n % 3
			n = n // 3
			if a > 1:
				s = 1
				break
		if s == 0:
			print()
			print(i)
			break
		i += 1
		n = i


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)


testes = {}
t = int(input())
for i in range(t):
	entrada = int(input())
	copia = entrada
	if entrada in testes:
		print(testes[entrada])
	else:
		atual = 0
		while True:
			ok = True
			atual = entrada
			while atual > 0:
				if ok == True and atual % 3 == 2:
					ok = False
				atual = atual // 3
			if ok:
				break
			entrada = entrada + 1
		testes[copia] = entrada
		print(entrada)


arr = [0, 1, 3, 4, 9, 10, 12, 13, 27, 28, 30, 31, 36, 37, 39, 40, 81, 82, 84, 85, 90, 91, 93, 94, 108, 109, 111, 112, 117, 118, 120, 121, 243, 244, 246, 247, 252, 253, 255, 256, 270, 271, 273, 274, 279, 280, 282, 283, 324, 325, 327, 328, 333, 334, 336, 337, 351, 352, 354, 355, 360, 361, 363, 364, 729, 730, 732, 733, 738, 739, 741, 742, 756, 757, 759, 760, 765, 766, 768, 769, 810, 811, 813, 814, 819, 820, 822, 823, 837, 838, 840, 841, 846, 847, 849, 850, 972, 973, 975, 976, 981, 982, 984, 985, 999, 1000, 1002, 1003, 1008, 1009, 1011, 1012, 1053, 1054, 1056, 1057, 1062, 1063, 1065, 1066, 1080, 1081, 1083, 1084, 1089, 1090, 1092, 1093, 2187, 2188, 2190, 2191, 2196, 2197, 2199, 2200, 2214, 2215, 2217, 2218, 2223, 2224, 2226, 2227, 2268, 2269, 2271, 2272, 2277, 2278, 2280, 2281, 2295, 2296, 2298, 2299, 2304, 2305, 2307, 2308, 2430, 2431, 2433, 2434, 2439, 2440, 2442, 2443, 2457, 2458, 2460, 2461, 2466, 2467, 2469, 2470, 2511, 2512, 2514, 2515, 2520, 2521, 2523, 2524, 2538, 2539, 2541, 2542, 2547, 2548, 2550, 2551, 2916, 2917, 2919, 2920, 2925, 2926, 2928, 2929, 2943, 2944, 2946, 2947, 2952, 2953, 2955, 2956, 2997, 2998, 3000, 3001, 3006, 3007, 3009, 3010, 3024, 3025, 3027, 3028, 3033, 3034, 3036, 3037, 3159, 3160, 3162, 3163, 3168, 3169, 3171, 3172, 3186, 3187, 3189, 3190, 3195, 3196, 3198, 3199, 3240, 3241, 3243, 3244, 3249, 3250, 3252, 3253, 3267, 3268, 3270, 3271, 3276, 3277, 3279, 3280, 6561, 6562, 6564, 6565, 6570, 6571, 6573, 6574, 6588, 6589, 6591, 6592, 6597, 6598, 6600, 6601, 6642, 6643, 6645, 6646, 6651, 6652, 6654, 6655, 6669, 6670, 6672, 6673, 6678, 6679, 6681, 6682, 6804, 6805, 6807, 6808, 6813, 6814, 6816, 6817, 6831, 6832, 6834, 6835, 6840, 6841, 6843, 6844, 6885, 6886, 6888, 6889, 6894, 6895, 6897, 6898, 6912, 6913, 6915, 6916, 6921, 6922, 6924, 6925, 7290, 7291, 7293, 7294, 7299, 7300, 7302, 7303, 7317, 7318, 7320, 7321, 7326, 7327, 7329, 7330, 7371, 7372, 7374, 7375, 7380, 7381, 7383, 7384, 7398, 7399, 7401, 7402, 7407, 7408, 7410, 7411, 7533, 7534, 7536, 7537, 7542, 7543, 7545, 7546, 7560, 7561, 7563, 7564, 7569, 7570, 7572, 7573, 7614, 7615, 7617, 7618, 7623, 7624, 7626, 7627, 7641, 7642, 7644, 7645, 7650, 7651, 7653, 7654, 8748, 8749, 8751, 8752, 8757, 8758, 8760, 8761, 8775, 8776, 8778, 8779, 8784, 8785, 8787, 8788, 8829, 8830, 8832, 8833, 8838, 8839, 8841, 8842, 8856, 8857, 8859, 8860, 8865, 8866, 8868, 8869, 8991, 8992, 8994, 8995, 9000, 9001, 9003, 9004, 9018, 9019, 9021, 9022, 9027, 9028, 9030, 9031, 9072, 9073, 9075, 9076, 9081, 9082, 9084, 9085, 9099, 9100, 9102, 9103, 9108, 9109, 9111, 9112, 9477, 9478, 9480, 9481, 9486, 9487, 9489, 9490, 9504, 9505, 9507, 9508, 9513, 9514, 9516, 9517, 9558, 9559, 9561, 9562, 9567, 9568, 9570, 9571, 9585, 9586, 9588, 9589, 9594, 9595, 9597, 9598, 9720, 9721, 9723, 9724, 9729, 9730, 9732, 9733, 9747, 9748, 9750, 9751, 9756, 9757, 9759, 9760, 9801, 9802, 9804, 9805, 9810, 9811, 9813, 9814, 9828, 9829, 9831, 9832, 9837, 9838, 9840, 9841, 19683]

def close(n):
	global arr
	for i in range(len(arr)):
		if arr[i] < n and arr[i + 1] >= n:
			print(arr[i + 1])
			break
t = int(input())
for _ in range(t):
	n = int(input())
	close(n)


cases = int(input())
pow_three = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683]
sum_pow_three = [1, 4, 13, 40, 121, 364, 1093, 3280, 9841]
for case in range(cases):
	number = int(input())
	index = -1
	ans = 0
	while True:
		if ans + pow_three[index - 1] < number and ans + sum_pow_three[index] < number:
			ans += pow_three[index]
			break
		if number == ans + sum_pow_three[index]:
			ans += sum_pow_three[index]
			break
		if number == ans + pow_three[index - 1]:
			ans += pow_three[index - 1]
			break
		if ans + pow_three[index - 1] < number < ans + sum_pow_three[index]:
			ans += pow_three[index - 1]
		index -= 1
	print(ans)


import sys
q = int(input())
for _ in range(q):
	n = int(input())
	b = []
	while n > 0:
		b.append(n % 3)
		n = int(n / 3)
	c = 0
	for p in range(len(b)):
		b[p] += c
		c = 0
		if b[p] <= 1:
			continue
		for u in range(p + 1):
			b[u] = 0
		c = 1
	if c:
		b.append(1)
	m = 0
	p = 0
	cur = 1
	while p < len(b):
		m += b[p] * cur
		p += 1
		cur *= 3
	print(m)


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)


def tripple(x):
	g = [0 for i in range(10)]
	i = 0
	while x != 0:
		t = 0
		for i in range(x):
			t = 3 ** i
			if t == x:
				g[i] += 1
				break
			if t > x:
				g[i - 1] += 1
				t = 3 ** (i - 1)
				break
		x -= t
	return g

def plus(g):
	g[0] += 1
	while is_not(g, 3) != -1:
		t = is_not(g, 3)
		g[t] -= 3
		g[t + 1] += 1
	return g

def is_not(g, dif):
	for i in range(len(g)):
		if g[i] >= dif:
			return i
	return -1

def numbers(x):
	t = tripple(x)
	g = is_not(t, 2)
	while g != -1:
		for i in range(0, g + 1):
			t[i] = 0
		t[g] = 0
		t[g + 1] += 1
		f = is_not(t, 3)
		while f != -1:
			t[f] -= 3
			t[f + 1] += 1
			f = is_not(t, 3)
		g = is_not(t, 2)
	result = 0
	for i in range(len(t)):
		if t[i] != 0:
			result += 3 ** i
	return result
for i in range(int(input().strip())):
	print(numbers(int(input().strip())))


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))


coins = [3 ** i for i in range(26)]
t = 1 << 12
sm = []
for i in range(t):
	c = 0
	for j in range(12):
		if i & 1 << j:
			c += coins[j]
	sm.append(c)
sm.sort()
from bisect import bisect_left as bl
for _ in range(int(input())):
	n = int(input())
	ind = bl(sm, n)
	print(sm[ind])


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()


powers = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683]
powers.reverse()
q = int(input())
for qq in range(0, q):
	n = int(input())
	_break = False
	for num in range(n, 19684):
		onum = num
		for power in powers:
			if num >= power:
				num = num - power
			if num == 0:
				res = onum
				_break = True
				break
		if _break:
			break
	print(res)


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)


q = int(input())
k = 0
while k < q:
	Mass = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683]
	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:
		razn = number - answer
		answer += Mass[0]
		for i in Mass2:
			answer -= i
			if answer < number:
				answer += i
				break
	print(answer)
	k += 1


q = int(input())
a = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683]
for _ in range(q):
	n = int(input())
	ans = 0
	for bit in range(2 ** len(a)):
		v = sum((a[i] for i in range(len(a)) if 2 ** i & bit))
		if v >= n:
			ans = v
			break
	print(ans)


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()


power = []
f = 0
for i in range(0, 1000):
	p = pow(3, i)
	f = i
	if p <= 1000000:
		power.append(p)
	else:
		break
arr = []
total = 1 << len(power)
for i in range(0, total):
	su = 0
	for j in range(0, len(power)):
		if i & 1 << j:
			su = su + power[j]
	arr.append(su)
t = int(input())
for _ in range(t):
	n = int(input())
	arr.sort()
	if n in arr:
		print(n)
	else:
		m = 0
		m1 = 0
		for i in range(0, len(power)):
			if n < power[i]:
				m = power[i]
				break
		for i in range(0, len(arr)):
			if n < arr[i]:
				m1 = arr[i]
				break
		print(min(m, m1))


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)


from sys import stdin
input = stdin.readline
from heapq import heapify, heappush, heappop, heappushpop
from collections import defaultdict as dd, deque as dq, Counter as C
from math import factorial as f, ceil, gcd, sqrt, log
from bisect import bisect_left as bl, bisect_right as br
from itertools import combinations as c, permutations as p
from math import factorial as f, ceil, gcd, sqrt, log
mp = lambda : map(int, input().split())
it = lambda : int(input())
ls = lambda : list(input().strip())
mt = lambda r: [list(mp()) for _ in range(r)]
lcm = lambda a, b: a * b // gcd(a, b)

def fibo_n(n):
	return ((1 + sqrt(5)) / 2) ** n / sqrt(5)
mod = 1000000007
n = 10 ** 4 + 1
v = [1]
while v[-1] <= n:
	v.append(v[-1] * 3)
v.append(v[-1] * 3)
v.append(v[-1] * 3)

def checkcur(n):
	for j in range(len(v) - 1, -1, -1):
		if n >= v[j]:
			n -= v[j]
	return n
for _ in range(it()):
	a = it()
	curel = a
	k = br(v, curel)
	nxt = v[k - 1]
	if curel == nxt:
		print(curel)
		continue
	while checkcur(curel):
		curel += 1
	print(curel)


arr = [1]
po = 1
while True:
	po = po * 3
	if po < 100000:
		arr.append(po)
	else:
		break
sum_arr = []
for i in range(0, 2 ** len(arr)):
	bi = bin(i)[2:]
	while len(bi) != len(arr):
		bi = '0' + bi
	su = 0
	set_bit = 0
	rev_bi = bi[::-1]
	for j in range(0, len(rev_bi)):
		if rev_bi[j] == '1':
			su += arr[j]
			set_bit += 1
	sum_arr.append((su, set_bit))
T = int(input())
while T > 0:
	n = int(input())
	ans = []
	for i in range(0, len(sum_arr)):
		if sum_arr[i][0] >= n:
			ans = sum_arr[i][0]
			break
	print(ans)
	T -= 1


lstm = []
lst = [0] * 16
t = 1
for i in range(16):
	lst[i] = t
	t *= 3
arr = []
for i in range(20000):
	tt = []
	tt.append(0)
	tt.append([])
	arr.append(tt)
arr[0][0] = 1
ans = [0] * 20001
for i in range(20000):
	foo = 0
	for j in lst:
		if j > i:
			break
		if arr[i - j][0] == 1:
			if j not in arr[i - j][1]:
				foo = 1
				arr[i][1] = arr[i - j][1].copy()
				arr[i][1].append(j)
				lstm.append(i)
				break
	if foo == 1:
		arr[i][0] = 1
temp = 0
for i in range(19999, -1, -1):
	if arr[i][0] == 1:
		temp = i
	ans[i] = temp
for y in range(int(input())):
	n = int(input())
	print(ans[n])


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)


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

def si():
	return input()

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

def li():
	return list(mi())
import math
q = ii()
for i in range(q):
	n = ii()
	c = 0
	while pow(3, c) < n:
		c += 1
	if pow(3, c) == n:
		print(pow(3, c))
		continue
	ans = pow(3, c)
	b = 1 << c - 1 + 1
	for i in range(b):
		d = pow(3, c - 1)
		for j in range(c - 1):
			if (i >> j) % 2:
				d += pow(3, j)
		if d >= n:
			ans = d
			break
	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 bisect
q = int(input())
check = [None for i in range(20000)]
check[1] = 1
track = [1]
for i in range(2, 20000):
	if i % 3 == 0:
		if check[i // 3] == 1:
			check[i] = 1
		else:
			check[i] = 0
	if i % 3 == 1:
		if check[i - 1] == 1:
			check[i] = 1
		else:
			check[i] = 0
	if i % 3 == 2:
		check[i] = 0
	if check[i] == 1:
		track.append(i)
for _ in range(q):
	n = int(input())
	print(track[bisect.bisect_left(track, n)])


from bisect import bisect_left
q = int(input())
answers = [0] * q
MaxPower = 10
PowersThree = [0] * MaxPower
PowersThree[0] = 1
n = [0] * q
for i in range(1, MaxPower):
	PowersThree[i] = PowersThree[i - 1] * 3
for i in range(q):
	n[i] = int(input())
PowerInd = [0] * MaxPower
STP = False
Values = []
while not STP:
	PowerInd[0] += 1
	for i in range(MaxPower):
		if PowerInd[i] == 2:
			PowerInd[i] = 0
			if i == MaxPower - 1:
				STP = True
			else:
				PowerInd[i + 1] += 1
	Sum = sum([a * b for (a, b) in zip(PowerInd, PowersThree)])
	Values.append(Sum)
for i in range(q):
	ind = bisect_left(Values, n[i])
	print(Values[ind])


from itertools import combinations
x = []
for i in range(10):
	x.append(pow(3, i))
sol = []
for i in range(1, 10):
	comb = combinations(x, i)
	for i in list(comb):
		sol.append(sum(i))
sol.sort()
for _ in range(int(input())):
	n = int(input())
	for i in sol:
		if i >= n:
			print(i)
			break


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


t = int(input())
gn = []
for aa in range(2):
	for a in range(2):
		for b in range(2):
			for c in range(2):
				for d in range(2):
					for e in range(2):
						for f in range(2):
							for g in range(2):
								for h in range(2):
									for i in range(2):
										gn.append(aa * 3 ** 9 + a * 3 ** 8 + b * 3 ** 7 + c * 3 ** 6 + d * 3 ** 5 + e * 3 ** 4 + f * 3 ** 3 + g * 3 ** 2 + h * 3 + i)
for _ in range(t):
	n = int(input())
	for i in gn:
		if i >= n:
			print(i)
			break


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 ternaryRepresentation():

	def if_two_in_Ternary(n):
		if n == 0:
			return '0'
		nums = []
		while n:
			(n, r) = divmod(n, 3)
			if r == 2:
				return False
			nums.append(str(r))
		return True
	q = int(input())
	for _ in range(q):
		n = int(input())
		for num in range(n, 3 * n):
			if if_two_in_Ternary(num):
				print(num)
				break
ternaryRepresentation()


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)


from sys import stdin, stdout
import sys
from bisect import bisect_left, bisect_right
import gc
gc.disable()

def get_bin(l, num):
	temp = str(bin(num)[2:])
	temp = (l - len(temp)) * '0' + temp
	return temp

def get_subset(start, end):
	aux = [3 ** x for x in range(start, end + 1)]
	aux2 = []
	l = end - start + 1
	for k in range(1, 2 ** (end - start + 1)):
		b = get_bin(l, k)
		temp = 0
		for j in range(len(b)):
			if b[j] == '1':
				temp += aux[j]
		aux2.append(temp)
	aux2.sort()
	return aux2

def query(n):
	if n <= first[-1]:
		return first[bisect_left(first, n)]
	else:
		index = bisect_left(second, n)
		if second[index] == n or index == 0:
			return second[index]
		index2 = bisect_left(first, n - second[index - 1])
		if index2 < len(first):
			return first[index2] + second[index - 1]
		else:
			return second[index]
first = get_subset(0, 4)
second = get_subset(5, 9)
q = int(stdin.readline().strip())
for _ in range(q):
	n = int(stdin.readline().strip())
	print(query(n))


q = int(input())
l = [1]
var = 1
for t in range(q):
	n = int(input())
	while True:
		temp = pow(3, var)
		l.append(temp)
		if temp >= n:
			break
		for i in l:
			if i < temp:
				l.append(i + temp)
			else:
				break
		var += 1
	val = 1
	for i in l:
		val = i
		if i >= n:
			break
	print(val)


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


from sys import stdin, stdout
import bisect
import math

def st():
	return list(stdin.readline().strip())

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

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

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

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

def soe(limit):
	l = [1] * (limit + 1)
	prime = []
	for i in range(2, limit + 1):
		if l[i]:
			for j in range(i * i, limit + 1, i):
				l[j] = 0
	for i in range(2, limit + 1):
		if l[i]:
			prime.append(i)
	return prime

def segsoe(low, high):
	limit = int(high ** 0.5) + 1
	prime = soe(limit)
	n = high - low + 1
	l = [0] * (n + 1)
	for i in range(len(prime)):
		lowlimit = low // prime[i] * prime[i]
		if lowlimit < low:
			lowlimit += prime[i]
		if lowlimit == prime[i]:
			lowlimit += prime[i]
		for j in range(lowlimit, high + 1, prime[i]):
			l[j - low] = 1
	for i in range(low, high + 1):
		if not l[i - low]:
			if i != 1:
				print(i)

def gcd(a, b):
	while b:
		a = a % b
		(b, a) = (a, b)
	return a

def power(a, n):
	r = 1
	while n:
		if n & 1:
			r = r * a
		a *= a
		n = n >> 1
	return r

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

def solve():
	n = inp()
	while True:
		if check(n):
			print(n)
			break
		n += 1
for _ in range(inp()):
	solve()


a = []
a.append(1)
a.append(3)
a.append(4)
for i in range(2, 9):
	var = 3 ** i
	a.append(var)
	for j in range(len(a) - 1):
		a.append(var + a[j])
a.append(19683)
l = [0] * 19684
j = 0
for i in range(len(a)):
	l[a[i]] = a[i]
for i in range(19682, 0, -1):
	if l[i] == 0:
		l[i] = l[i + 1]
q = int(input())
while q:
	n = int(input())
	print(l[n])
	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)


a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
from itertools import combinations
import bisect
c = []
for i in range(1, 10):
	c += list(combinations(a, i))
p = set()
for i in range(len(c)):
	l = 0
	for j in range(len(c[i])):
		l += pow(3, c[i][j])
	p.add(l)
p = list(p)
p = sorted(p)
q = int(input())
for _ in range(q):
	n = int(input())
	k = bisect.bisect_left(p, n)
	if p[k] == n:
		print(n)
	else:
		print(p[k])


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 sys
input = sys.stdin.readline
q = int(input())
import bisect as bi
l = [1, 3, 9, 27, 81, 243, 729, 2187, 6561]
ll = []
for i in range(1, 2 ** 9):
	x = 0
	for j in range(9):
		if i >> j & 1 == 1:
			x += l[j]
	ll.append(x)
ll.append(19683)
ll.append(10 ** 6)
for _ in range(q):
	n = int(input())
	x = bi.bisect_left(ll, n)
	if n <= ll[x]:
		print(ll[x])
	else:
		print(ll[x + 1])


def check(a):
	while a > 1:
		while a % 3 == 0:
			a //= 3
		a -= 1
		if a % 3 != 0:
			return False
	return True
q = int(input())
ans = []
for i in range(q):
	N = int(input())
	i = N
	while True:
		if check(i):
			ans.append(i)
			break
		else:
			i += 1
print(*ans, sep='\n')


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)


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

def tellme(n, used):
	p = int(log(n, 3))
	if n % 3 != 0:
		n -= 1
		used.append(1)
	if n == 0:
		return True
	else:
		po = 3 ** p
		if po in used:
			return False
		elif n == po or (1162261467 % n == 0 and n not in used):
			return True
		else:
			used.append(po)
			return tellme(n - po, used)
for i in range(q):
	n = int(input())
	if (n - 1) % 3 == 0:
		start = n
		jump = 2
	elif n % 3 == 0:
		start = n
		jump = 1
	else:
		start = n + 1
		jump = 1
	while not tellme(start, []):
		start += jump
		jump = 2 if jump == 1 else 1
	l.append(start)
print('\n'.join((str(k) for k in l)))


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)


import sys

def check(x):
	while x != 0:
		if x % 3 == 2:
			return False
		x = x // 3
	return True
q = int(sys.stdin.readline())
ans_arr = []
for i in range(q):
	n = int(sys.stdin.readline())
	val = n
	while not check(val):
		val += 1
	ans_arr.append(str(val))
print('\n'.join(ans_arr))


q = int(input())
l = []
for i in range(2048):
	bs = bin(i)[2:].zfill(10)
	cnt = 0
	for (i, b) in enumerate(bs[::-1]):
		cnt += int(b) * 3 ** i
	l.append(cnt)
l.sort()
from bisect import bisect_left
for _ in range(q):
	n = int(input())
	ind = bisect_left(l, n)
	print(l[ind])


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 block(x):
	v = []
	while x > 0:
		v.append(int(x % 3))
		x = int(x / 3)
	t = []
	for i in range(0, len(v)):
		if v[i] == 1:
			t.append(i)
	return t

def trai(x):
	o = block(x)
	if len(o) == 0:
		return 0
	else:
		count = 0
		for i in range(len(o)):
			count = count + 3 ** o[i]
		if count == x:
			return 1
		else:
			return 0
r = []
for i in range(1, 10 ** 4 + 1):
	if trai(i) == 1:
		r.append(i)
r.append(19683)
k = int(input())
for j in range(k):
	y = int(input())
	i = 0
	while y > r[i]:
		i = i + 1
	print(r[i])


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()


t = int(input())
l = list()
l.append(1)
for i in range(1, 10):
	x = 3 ** i
	a = len(l)
	for i in range(a):
		l.append(l[i] + x)
	l.append(x)
l.sort()
for _ in range(t):
	n = int(input())
	ans = 1
	for i in l:
		if i >= n:
			ans = i
			break
	print(ans)


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 is_num_good(num):
	while num > 0:
		if num % 3 == 2:
			return False
		num = num // 3
	return True
num_queries = int(input())
good_numbers = {}
for num in range(1, 2 * 10 ** 4):
	good_numbers[num] = is_num_good(num)
for _ in range(num_queries):
	num = int(input())
	while True:
		if good_numbers[num]:
			break
		num += 1
	print(num)


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 os
import sys
from io import BytesIO, IOBase
from bisect import bisect

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 solution(n):
	ter = list(ternary(n))
	if '2' in ter:
		two = ter.index('2')
		if '0' in ter[:two]:
			tn = len(ter)
			ze = ''.join(ter[:two]).rfind('0')
			ter[ze] = '1'
			for i in range(ze + 1, tn):
				ter[i] = '0'
			p = tn - 1
			res = 0
			for c in ter:
				res += int(c) * 3 ** p
				p -= 1
			write(res)
		else:
			write(3 ** len(ter))
	else:
		write(n)

def main():
	for _ in range(r_int()):
		n = r_int()
		solution(n)
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))

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

def write(*args, end='\n'):
	for x in args:
		sys.stdout.write(str(x) + ' ')
	sys.stdout.write(end)

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

def r_int():
	return int(input())
main()


from bisect import bisect_right as bi
a = []
c = []
for i in range(10):
	a.append(pow(3, i))
for i in range(1024):
	b = bin(i)[2:]
	b = '0' * (10 - len(b)) + b
	x = 0
	for j in range(10):
		if b[j] == '1':
			x += a[j]
	c.append(x)
c.sort()
for _ in range(int(input())):
	n = int(input())
	x = bi(c, n)
	if x > 0 and c[x - 1] == n:
		print(c[x - 1])
	else:
		print(c[x])


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)


from itertools import combinations
po = [1]
for i in range(1, 10):
	po.append(po[-1] * 3)
tot = set()
for i in range(1, len(po) + 1):
	x = list(combinations(po, i))
	for i in x:
		tot.add(sum(list(i)))
tot = list(tot)
tot.sort()
for _ in range(int(input())):
	n = int(input())
	for i in tot:
		if i >= n:
			print(i)
			break


import itertools

def findsubsets(s, n):
	return list(itertools.combinations(s, n))
ans = [0 for i in range(20000)]
p = [3 ** i for i in range(10)]
for i in range(10):
	l = findsubsets(p, i)
	for j in l:
		t = sum(j)
		if t <= 20000:
			ans[t] = t
i = 19999
p = ans[i]
while i >= 0:
	if ans[i] != 0:
		p = ans[i]
	else:
		ans[i] = p
	i = i - 1
q = int(input())
while q > 0:
	q = q - 1
	s = int(input())
	print(ans[s])


import sys

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

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

def oint():
	return int(input())
q = oint()
for _ in range(q):
	n = oint()
	mindiff = 10 ** 10
	ans = 0
	for i in range(2 ** 10):
		s = bin(i)[2:]
		ss = int(s, 3)
		if ss >= n:
			diff = ss - n
			if diff < mindiff:
				mindiff = diff
				ans = ss
	print(ans)


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))


from sys import stdin, stdout
from math import ceil, log, floor
import bisect
maxpower = floor(log(10 ** 4, 3))
powers = [1]
t = 1
for i in range(1, maxpower + 1):
	t *= 3
	powers.append(t)
from itertools import chain, combinations

def powerset(iterable):
	s = list(iterable)
	return chain.from_iterable((combinations(s, r) for r in range(len(s) + 1)))
allsums = []
for i in powerset(powers):
	allsums.append(sum(i))
allsums = list(allsums)
allsums.sort()
q = int(input())
for _ in range(q):
	n = int(input())
	if n > 9841:
		print(19683)
	else:
		ind = bisect.bisect_left(allsums, n)
		print(allsums[ind])


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)


t = int(input())
for _ in range(t):
	n = int(input())
	while True:
		x = n
		flag = True
		while x != 0:
			if x % 3 == 2:
				flag = False
				break
			x = int(x / 3)
		if flag:
			print(n)
			break
		n += 1


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 _ in range(int(input())):
	a = int(input())
	i = 3
	while i / 3 < a:
		if a % i >= i / 3 * 2:
			a -= a % i - i
		i *= 3
	print(a)


def convert(no):
	arr = []
	while no:
		arr.append(no % 3)
		no //= 3
	arr.reverse()
	return 2 not in arr
perfect = [i for i in range(1, 2 * 10 ** 4) if convert(i)]
import bisect
for _ in range(int(input())):
	n = int(input())
	print(perfect[bisect.bisect_left(perfect, n)])


MAX_POWER = 9
POWERS_OF_THREE = [3 ** (MAX_POWER - i) for i in range(MAX_POWER + 1)]

def gen_numbers(l, x=0):
	if not l:
		return [x]
	temp_var_i_cannot_name = []
	temp_var_i_cannot_name += gen_numbers(l[1:], x)
	temp_var_i_cannot_name += gen_numbers(l[1:], x + l[0])
	return temp_var_i_cannot_name
GOOD_NUMBERS = gen_numbers(POWERS_OF_THREE)
num_queries = int(input())
for _ in range(num_queries):
	n = int(input())
	for m in GOOD_NUMBERS:
		if m >= n:
			print(m)
			break


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)


from itertools import combinations
for _ in range(int(input())):
	n = int(input())
	re = 0
	initial = 0
	while re <= n:
		re += 3 ** initial
		initial += 1
	end = initial
	power = list(range(initial))
	good = []
	for i in range(len(power)):
		comb = combinations(power, i)
		for j in list(comb):
			goo = 0
			for k in j:
				goo += 3 ** k
			good.append(goo)
	good.sort()
	for g in good:
		if n <= g:
			print(g)
			break


from bisect import bisect_right
l = []
for i in range(10):
	l.append(3 ** i)
	ar = []
s = []
s = set(s)
from itertools import combinations

def powerset(string):
	for i in range(0, len(string) + 1):
		for element in combinations(string, i):
			temp = 0
			for j in element:
				temp += j
			s.add(temp)
powerset(l)
s = list(s)
k = s.copy()
s.append(1)
s.sort()
k = s.copy()
k = set(s)
for _ in range(int(input())):
	n = int(input())
	if n in k:
		print(n)
	else:
		temp = bisect_right(s, n)
		print(s[temp])


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)


po = []
for n in range(10):
	po.append(3 ** n)
from itertools import chain, combinations

def powerset(iterable):
	s = list(iterable)
	return chain.from_iterable((combinations(s, r) for r in range(len(s) + 1)))
sums = sorted(map(sum, powerset(po)))
import bisect
skaits = int(input())
for ii in range(skaits):
	inn = int(input())
	if inn in sums:
		print(inn)
	else:
		index = bisect.bisect(sums, inn)
		print(sums[index])


def convert_to_3(n):
	if n < 3:
		return alf[n]
	else:
		return convert_to_3(n // 3) + alf[n % 3]
(good, alf) = (set(), '012')
for i in range(1, int(20000.0)):
	if '2' not in convert_to_3(i):
		good.add(i)
for q in range(int(input())):
	n = int(input())
	while n not in good:
		n += 1
	print(n)


def check(n1):
	while n1 > 0:
		if n1 % 3 == 2:
			return False
		else:
			n1 //= 3
	return True
for t in range(int(input())):
	n = int(input()) - 1
	s = True
	while s:
		n += 1
		s = not check(n)
	print(n)


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))


class ProblemC:

	def __init__(self, tc):
		self.tc = tc
		self.pofThree = [3 ** i for i in range(20)]

	def Solve(self):
		for i in range(self.tc):
			s = sum(self.pofThree)
			num = int(input())
			for t in self.pofThree[::-1]:
				if s - t >= num:
					s -= t
			print(s)
o = ProblemC(int(input()))
o.Solve()


l = []
l.append(0)
l.append(1)
ele = 0
j = 1
while ele <= 10000:
	j = j * 3
	t = len(l)
	for i in range(t):
		ele = j + l[i]
		l.append(ele)
		if ele > 10000:
			break
for _ in range(int(input())):
	n = int(input())
	for i in l:
		if i >= n:
			print(i)
			break


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)


arr = [3 ** i for i in range(10)]
brr = []
for i in range(520):
	st = '{0:b}'.format(i)
	val = 0
	for (i, ch) in enumerate(st[::-1]):
		val += arr[i] * int(ch)
	brr.append(val)
case = int(input())
for _ in range(case):
	n = int(input())
	for i in range(520):
		if brr[i] >= n:
			print(brr[i])
			break


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)


def func(n):
	i = 15
	while i >= 1:
		if pow(3, i) <= n:
			n -= pow(3, i)
		i -= 1
	if n <= 1:
		return True
	return False
l = list()
for i in range(1, 20000):
	if func(i) == True:
		l.append(i)
for _ in range(int(input())):
	n = int(input())
	for i in l:
		if i >= n:
			print(i)
			break


pos = [0] * 20000

def f(cs, cp):
	if cs < 20000 and cp < 12:
		pos[cs] = 1
		f(cs, cp + 1)
		f(cs + 3 ** cp, cp + 1)
f(0, 0)
fc = 0
for i in range(20000 - 1, 0, -1):
	if pos[i] == 1:
		fc = i
	pos[i] = fc
for _ in range(int(input())):
	print(pos[int(input())])


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)


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


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)


import math
for _ in range(int(input())):
	n = int(input())
	ans = 0
	closest = math.ceil(math.log(n) / math.log(3))
	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 = math.floor(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 += math.pow(3, i)
	print(int(sm))


cases = int(input())
for i in range(cases):
	n = int(input())
	while True:
		ok = True
		number = n
		while number > 0:
			if ok and number % 3 == 2:
				ok = False
			number = int(number / 3)
		if ok:
			break
		n += 1
	print(n)


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))


arr = []
arr.append(0)
arr.append(1)
cnt = 3
for i in range(10):
	for j in range(len(arr)):
		arr.append(cnt + arr[j])
	cnt = cnt * 3
for _ in range(int(input())):
	n = int(input())
	for x in arr:
		if x >= n:
			print(x)
			break


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)


from math import ceil, sqrt, floor, sqrt
import collections
from typing import List
t = int(input())
for _ in range(t):
	n = int(input())
	dp = {0}
	val = 1
	while True:
		min_good = None
		for cur in list(dp):
			dp.add(cur + val)
			if cur + val >= n:
				if min_good is None:
					min_good = cur + val
				else:
					min_good = min(min_good, cur + val)
		if min_good is not None:
			print(min_good)
			break
		val *= 3


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))


from sys import stdin
input = lambda : stdin.readline().rstrip('\r\n')
input_a = lambda fun: map(fun, stdin.readline().split())
a = []
for i in range(10):
	p = 3 ** i
	sums = [p + x for x in a]
	a.append(p)
	a.extend(sums)

def read():
	return int(input())

def solve(n):
	i = 0
	while a[i] < n:
		i += 1
	return a[i]
for t in range(int(input())):
	result = solve(read())
	print(result)


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
from collections import deque, defaultdict, OrderedDict
import collections

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	zz = 0
	u = 0
	pow3 = []
	while pow(3, u) <= 20000:
		pow3.append(pow(3, u))
		u += 1
	ls = []
	from itertools import permutations
	for i in range(len(pow3)):
		s3 = list(itertools.combinations(pow3, i + 1))
		for i in s3:
			ls.append(sum(i))
	ls = sorted(ls)
	for _ in range(ri()):
		a = ri()
		for i in ls:
			if i >= a:
				print(i)
				break
	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()


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 binary(x):
	z = []
	if x == 0:
		z.append(0)
		return z
	while x != 0:
		z.append(x % 2)
		x = int(x / 2)
	return z
a = []
i = 0
check = 0
while check <= 10000:
	temp = binary(i)
	j = 0
	s = 0
	for k in temp:
		s += k * 3 ** j
		j += 1
	check = s
	a.append(check)
	i += 1
q = int(input())
while q != 0:
	n = int(input())
	for i in a:
		if i >= n:
			print(i)
			break
	q -= 1


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)


import math
t = int(input())
for i in range(t):
	n = int(input())
	result = int(math.log(n, 3))
	if result == 0:
		result = 1
	powers = [1] * (result + 1)
	for i in range(1, result + 1):
		powers[i] = powers[i - 1] * 3
	if n == 1:
		print(1)
	elif n == powers[result]:
		print(n)
	else:
		answer = powers[result]
		if answer >= n:
			print(answer)
		else:
			result = len(powers)
			powers.append(powers[result - 1] * 3)
			answer = 0
			j = 1
			while answer < n:
				stringname = bin(j)[2:]
				string = stringname[::-1]
				answer = 0
				for k in range(len(string)):
					if string[k] == '1':
						answer += powers[k]
				j += 1
			print(answer)


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)


a = [1]
for i in range(3, 20001):
	s = ''
	j = i
	while j > 0:
		s = str(j % 3) + s
		j = j // 3
	if '2' not in s:
		a.append(i)
for z in range(int(input())):
	n = input()
	if int(n) in a:
		print(n)
	else:
		for k in a:
			if k - int(n) > 0:
				print(k)
				break


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


pow3 = [pow(3, x) for x in range(10)][::-1]
sum_pow3 = sum(pow3)
nb = int(input())
for _ in range(nb):
	curr = int(input())
	sums = sum_pow3
	for i in pow3:
		if sums - i >= curr:
			sums -= i
	print(sums)


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))


import sys
import math
import itertools
import bisect

def find_ge(a, x):
	i = bisect.bisect_left(a, x)
	if i != len(a):
		return a[i]
	raise ValueError

def main():
	maxVal = 10 ** 5
	bitVectorLength = math.floor(math.log(10 ** 5, 3)) + 1
	goodNums = []
	for vec in itertools.product([True, False], repeat=bitVectorLength):
		num = 0
		for (i, bit) in enumerate(vec):
			if bit:
				num += 3 ** i
		if num > 0:
			goodNums.append(num)
	goodNums.sort()
	solns = []
	for _ in range(int(sys.stdin.readline())):
		n = int(sys.stdin.readline())
		if n in goodNums:
			solns.append(n)
		else:
			solns.append(find_ge(goodNums, n))
	return '\n'.join((str(x) for x in solns if x is not None))
print(main())


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))


import math
import copy

def f(base, inputNum):
	index = 0
	res = []
	while inputNum > 0:
		res.append(inputNum % base)
		inputNum = int(inputNum / base)
	return res
t = int(input())
j = -1
for _ in range(t):
	n = int(input())
	res = f(3, n)
	co = copy.deepcopy(res)
	c = 0
	j = -1
	for i in range(len(res)):
		if res[i] + c >= 2:
			c = 1
			j = i
		elif res[i] == 0 and c == 1:
			res[i] = 1
			c = 0
	if c == 1:
		res.append(1)
		j = len(res) - 2
	if j == -1:
		c = 0
		p = 1
		for i in range(len(res)):
			c += p * res[i]
			p = p * 3
		print(c)
	else:
		for i in range(0, j + 1):
			res[i] = 0
		c = 0
		p = 1
		for i in range(len(res)):
			c += p * res[i]
			p = p * 3
		print(c)


def main():
	q = int(input())
	t = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683]
	n = len(t)
	pos = 2 ** n
	powers = []
	for i in range(pos):
		sm = 0
		for j in range(n):
			if i & 1 << j:
				sm += t[j]
		powers.append(sm)
	for _ in range(q):
		n = int(input())
		for c in powers:
			if c >= n:
				print(c)
				break
main()


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)


from fractions import gcd
from datetime import date, timedelta
from heapq import *
import math
from collections import defaultdict, Counter, deque
import sys
from bisect import *
import itertools
import copy
sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7

def main():
	q = int(input())
	three = [0] * 100
	t = 1
	three[0] = 1
	for i in range(1, 100):
		t *= 3
		three[i] = t
	for i in range(q):
		n = int(input())
		ans = 0
		for i in range(90):
			ans += three[i]
		k = 90
		while ans >= n and k > -1:
			if ans - three[k] >= n:
				ans -= three[k]
			k -= 1
		print(ans)
main()


import bisect
i = 1
nums = []
while True:
	s = str(bin(i))[2:]
	i += 1
	gn = int(s, base=3)
	nums.append(gn)
	if gn > 10000.0:
		break
k = int(input())
for _ in range(k):
	x = int(input())
	i = bisect.bisect_left(nums, x)
	print(nums[i])


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)


l = [0]
t = 1
for i in range(0, 10000):
	l1 = []
	for i in l:
		l1.append(t + i)
	l.extend(l1)
	t *= 3
	if t > 30000:
		break
n = int(input())
l3 = []
for i in range(0, n):
	m = int(input())
	l3.append(m)
l2 = sorted(l3)
d = {}
i = 0
j = 0
while j < n:
	if l[i] >= l2[j]:
		d[l2[j]] = l[i]
		j += 1
	else:
		i += 1
for i in l3:
	print(d[i])


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 = [1] * 10
for i in range(10):
	l[i] = 3 ** i
q = int(input())
for _ in range(q):
	n = int(input())
	x = 0
	i = 0
	while n > x:
		x += l[i]
		i += 1
	if n == x:
		print(n)
	else:
		for j in range(9, -1, -1):
			if x - l[j] >= n:
				x = x - l[j]
		print(x)


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))


def check(i):
	if i == 0:
		return 1
	k = i % 3
	if k == 2:
		return 0
	else:
		m = (i - k) / 3
		if m % 1 != 0:
			return 0
		else:
			n = check(m)
			if n == 0:
				return 0
			else:
				return 1
g = [0] * 100001
for i in range(1, 100001):
	if check(i):
		g[i] = 1
t = int(input())
for _ in range(t):
	q = int(input())
	while g[q] != 1:
		q += 1
	print(q)


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))


foo = []
n = int(input())
for i in range(n):
	x = int(input())
	w = 3 ** 9
	q = x
	j = 10
	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 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))


import sys

def is_fit(n, base):
	while n > 0:
		mod = n % base
		if mod > 1:
			return False
		n = n // base
	return True
q = int(input())
ans = [0] * q
base = 3
for q_ in range(q):
	n = int(input())
	while True:
		if is_fit(n, base):
			ans[q_] = n
			break
		n += 1
print(*ans, sep='\n')


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

def good(n):
	return 2 not in base3(n)
for _ in range(int(input())):
	n = int(input())
	while not good(n):
		n += 1
	print(n)


import bisect
q = int(input())
n = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683]
z = len(n)
b = []
sum = 0
for a1 in range(0, 2):
	for a2 in range(0, 2):
		for a3 in range(0, 2):
			for a4 in range(0, 2):
				for a5 in range(0, 2):
					for a6 in range(0, 2):
						for a7 in range(0, 2):
							for a8 in range(0, 2):
								for a9 in range(0, 2):
									for a10 in range(0, 2):
										sum = 0
										if a1 == 1:
											sum += n[0]
										if a2 == 1:
											sum += n[1]
										if a3 == 1:
											sum += n[2]
										if a4 == 1:
											sum += n[3]
										if a5 == 1:
											sum += n[4]
										if a6 == 1:
											sum += n[5]
										if a7 == 1:
											sum += n[6]
										if a8 == 1:
											sum += n[7]
										if a9 == 1:
											sum += n[8]
										if a10 == 1:
											sum += n[9]
										b.append(sum)
b = sorted(b)
for a in range(q):
	c = int(input())
	ans = bisect.bisect_left(b, c)
	print(b[ans])


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


q = int(input())
a = set()
for i in range(10):
	l = 3 ** i
	b = set(a)
	for i in a:
		b.add(i + l)
	a = b
	a.add(l)
a = list(a)
a.sort()
for _ in range(q):
	n = int(input())
	for i in a:
		if i >= n:
			print(i)
			break


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 = int(input())
powers = [3 ** i for i in range(10)]
got = set()
from itertools import combinations
for i in range(1, len(powers) + 1):
	for j in combinations(powers, i):
		got.add(sum(j))
got = sorted(got)
for i in range(t):
	n = int(input())
	for j in got:
		if j >= n:
			print(j)
			break


q = int(input())

def solve(e, m, s):
	n = int(input())
	if m == n:
		print(m)
	elif m > n:
		o = m
		while o > n and o not in s:
			o -= 1
		if o == n:
			print(o)
		else:
			for x in s:
				if o + x >= n:
					print(o + x)
					break
	else:
		while m < n:
			e += 1
			m = pow(3, e)
			p = [x + m for x in s] + [m]
			s.update(p)
			sorted(s)
		o = m
		if o == n:
			print(n)
		if o > n:
			print(min(o, min([x for x in s if x >= n])))
for _ in range(q):
	e = 0
	m = 1
	s = {1}
	solve(e, m, s)


Max = 20000
dp = [0 for i in range(Max)]
dp[0] = dp[1] = 1
cur = 3
while cur < Max:
	end = Max - 1
	while end >= 0:
		if end + cur < Max and dp[end] == 1:
			dp[end + cur] = 1
		end -= 1
	cur = cur * 3
t = int(input())
for i in range(t):
	n = int(input())
	for j in range(n, Max):
		if dp[j] == 1:
			print(j)
			break


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)


from collections import deque
q = deque()
q.append((1, 0))
pos = [0] * 19686
ans = [0] * 19686
while q:
	r = q.popleft()
	pos[r[0]] = 1
	for i in range(r[1] + 1, 11):
		if r[0] + 3 ** i < 19685:
			q.append((r[0] + 3 ** i, i))
		if 3 ** i < 19685:
			q.append((3 ** i, i))
c = 19687
for i in range(len(pos) - 1, -1, -1):
	if pos[i] == 1:
		c = i
	ans[i] = c
q = int(input())
for _ in range(q):
	n = int(input())
	print(ans[n])


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()


def isgood(n):
	temp = n
	rem = []
	while temp != 0:
		rem.append(temp % 3)
		temp = int(temp / 3)
	if rem.count(2) == 0:
		return 1
	else:
		return 0
q = int(input())
dict1 = {}
for i in range(q):
	n = int(input())
	k = n
	while True:
		if k in dict1:
			print(dict1[k])
			break
		elif isgood(k) == 1:
			print(k)
			dict1[n] = k
			break
		else:
			k += 1


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()


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

def find1(n):
	res = 0
	power = 0
	while res <= n:
		res = 3 ** power
		power += 1
	power -= 1
	return [res, power]

def find2(temp):
	res = 0
	power = 0
	for k in range(len(table1)):
		if table1[k] > temp:
			res = table1[k - 1]
			power = k - 1
			break
		elif table1[k] == temp:
			res = table1[k]
			power = k
			break
	return [res, power]
for _ in range(q):
	n = int(sys.stdin.readline())
	(end, power1) = find1(n)
	table1 = [0] * (power1 + 1)
	for i in range(power1 + 1):
		table1[i] = 3 ** i
	judge = False
	for j in range(n, end + 1):
		table2 = [0] * (power1 + 1)
		if j == 3 ** (power1 - 1):
			judge = True
		else:
			temp = j
			(minus, power2) = find2(temp)
			while True:
				if temp == 0:
					judge = True
					break
				if temp >= 3 ** power2 and temp <= 3 ** (power2 + 1):
					pass
				else:
					for l in range(power2 + 1):
						if 3 ** l > temp:
							power2 = l - 1
							break
				if table2[power2] == 0:
					temp -= 3 ** power2
					table2[power2] = 1
				else:
					break
		if judge == True:
			print(j)
			break


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()


inp = lambda : int(input())
seq = lambda : list(map(int, input().strip().split()))

def count(n):
	while n != 0:
		if n % 3 == 2:
			return True
		n //= 3
	return False

def results(n):
	ans = n
	while count(ans):
		ans += 1
	return ans

def main():
	t = inp()
	for _ in range(t):
		n = inp()
		result = results(n)
		print(result)
main()


import itertools
from bisect import bisect_right
three = [1, 3, 9, 27, 81, 243, 729, 2187, 6561]
l = []
for L in range(1, len(three) + 1):
	for subset in itertools.combinations(three, L):
		l.append(sum(subset))
l.sort()
q = int(input())
for _ in range(q):
	n = int(input())
	if n == 9841:
		print(9841)
		continue
	if n > 9841:
		print(19683)
		continue
	elif l[bisect_right(l, n) - 1] >= n:
		print(l[bisect_right(l, n) - 1])
	else:
		print(l[bisect_right(l, n)])


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)


v = set()
v.add(0)
i = 1
while i <= 20000:
	nv = list(v)
	for x in nv:
		v.add(x + i)
	i = i * 3
ans = [0] * 10001
v = list(v)
v.sort()
j = 0
for i in range(1, 10001):
	if v[j] >= i:
		ans[i] = v[j]
	else:
		j += 1
		ans[i] = v[j]
t = int(input())
for _ in range(t):
	n = int(input())
	print(ans[n])


for i in range(int(input())):
	check = int(input())
	count = check
	flag = 0
	while flag == 0:
		new_num = ''
		while count > 0 and '2' not in new_num:
			new_num = str(count % 3) + new_num
			count //= 3
		if '2' not in new_num:
			print(check)
			flag = 1
		else:
			check += 1
			count = check


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)


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

def f(n, x, i, m):
	if x >= n:
		return x
	if i == m:
		return 3 ** m
	return min(f(n, x + 3 ** i, i + 1, m), f(n, x, i + 1, m))
for _ in range(int(input())):
	n = int(input())
	m = ceil(log(n, 3))
	ans = f(n, 0, 0, m)
	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()


def ternary(n):
	orders = []
	while n > 0:
		orders.append(n % 3)
		n //= 3
	return orders[::-1]

def decimal(a):
	p = 1
	s = 0
	for i in range(len(a) - 1, -1, -1):
		s += p * a[i]
		p *= 3
	return s

def maxpower(n):
	power = 0
	while n > 0:
		power += 1
		n //= 3
	return power

def isgood(n):
	while n > 0:
		if n % 3 > 1:
			return False
		n //= 3
	return True
q = int(input())
for _ in range(q):
	n = int(input())
	if n < 10 ** 14:
		while not isgood(n):
			n += 1
		print(n)
	else:
		t = ternary(n)
		i = len(t) - 1
		while i > 0:
			if t[i] > 1:
				for j in range(i, len(t)):
					t[j] = 0
				t[i - 1] += 1
			i -= 1
		if t[0] > 1:
			print(3 ** maxpower(n))
		else:
			print(decimal(t))


import bisect
arr = [3 ** i for i in range(23)]
t = int(input())
while t:
	n = int(input())
	a = sum(arr)
	for i in arr[::-1]:
		if a - i >= n:
			a -= i
	print(a)
	t -= 1


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


q = int(input())
a = []
for j in range(25):
	a.append(3 ** j)
a.reverse()
s = sum(a)
for i in range(q):
	ans = s
	n = int(input())
	for k in range(25):
		if ans - a[k] >= n:
			ans = ans - a[k]
	print(ans)


from bisect import bisect

def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))
p = []
for i in range(1, 20000):
	if not '2' in set(ternary(i)):
		p.append(i)
for _ in range(int(input())):
	n = int(input())
	if n in p:
		print(n)
	else:
		ind = bisect(p, n)
		print(p[ind])


from bisect import bisect_right
import itertools
table = list(itertools.product([0, 1], repeat=10))
l = list()
for (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) in table:
	l.append(pow(3, 0) * a1 + pow(3, 1) * a2 + pow(3, 2) * a3 + pow(3, 3) * a4 + pow(3, 4) * a5 + pow(3, 5) * a6 + pow(3, 6) * a7 + pow(3, 7) * a8 + pow(3, 8) * a9 + pow(3, 9) * a10)
l.sort()
t = int(input())
for _ in range(0, t):
	n = int(input())
	g = bisect_right(l, n)
	if g != 0 and l[g - 1] == n:
		print(n)
	else:
		print(l[g])


def solve():
	flag1 = False
	flag = False
	cur = 0
	mainnum = int(input())
	num = mainnum
	immediatenum = 0
	for i in range(50, -1, -1):
		if pow(3, i) > num:
			immediatenum = pow(3, i)
			flag1 = True
			if flag == True:
				flag1 = False
			cur = i
		elif pow(3, i) < num:
			num = num - pow(3, i)
			flag = True
		else:
			return mainnum
	if flag1 == True:
		return immediatenum
	return int(mainnum - (immediatenum - 1) / 2 + immediatenum - num)
for i in range(int(input())):
	print(solve())


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()


from math import floor, ceil, log

def good(n):
	used = set()
	while n > 0:
		k = log(n) / log(3)
		if ceil(k) - k < 1e-06:
			kk = ceil(k)
		else:
			kk = floor(k)
		if kk in used:
			return False
		used.add(kk)
		n -= 3 ** kk
	return True
q = int(input())
for _ in range(q):
	n = int(input())
	check = good(n)
	if check:
		print(n)
	else:
		ans = 0
		t = n
		while ans < n:
			i = 0
			while i <= 38:
				if 3 ** i > t:
					break
				i += 1
			if (3 ** i - 1) / 2 < t:
				ans += 3 ** i
				break
			else:
				t -= 3 ** (i - 1)
				ans += 3 ** (i - 1)
		print(ans)


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')


t = int(input())
from math import *
c = []
for i in range(0, 10):
	c.append(3 ** i)
	sumi = 3 ** i
	for j in range(len(c) - 1):
		sumi = 3 ** i + c[j]
		c.append(sumi)
import copy
while t > 0:
	t -= 1
	n = int(input())
	print(min((n1 for n1 in c if n1 >= 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))


nm3 = list()
for i in range(1, 1028):
	st = bin(i)
	st = st[2:]
	l = len(st)
	sm = 0
	for j in range(l):
		if st[l - 1 - j] == '1':
			sm += pow(3, j)
	nm3.append(sm)
for _ in range(int(input())):
	n = int(input())
	i = 0
	while nm3[i] < n:
		i += 1
	print(nm3[i])


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])


q = int(input())

def base_10_to_n(x, n):
	if int(x / n):
		return base_10_to_n(int(x / n), n) + str(x % n)
	return str(x % n)
for _ in range(q):
	n = int(input())
	s = list(base_10_to_n(n, 3))
	s.reverse()
	pos0 = -1
	pos2 = -1
	flag = False
	for i in range(len(s)):
		if s[i] == '2':
			pos2 = i
			flag = True
		if s[i] == '0' and flag:
			pos0 = i
			flag = False
	if pos2 != -1:
		if pos0 > pos2:
			temp = ['0'] * pos0 + ['1'] + s[pos0 + 1:]
			temp = list(map(int, temp))
			ans = 0
			for (i, d) in enumerate(temp):
				ans += d * 3 ** i
		else:
			ans = 3 ** len(s)
	else:
		ans = n
	print(ans)


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))


lis = [1]
power_int = 50

def init():
	for i in range(1, power_int):
		lis.append(lis[i - 1] * 3)

def solve():
	mainnum = int(input())
	num = mainnum
	largepower = lis[len(lis) - 1]
	smallpower = 0
	for i in range(len(lis) - 1, -1, -1):
		if num <= lis[i]:
			largepower = lis[i]
		else:
			num = num - lis[i]
			smallpower = smallpower + lis[i]
	return int(smallpower + largepower - (largepower - 1) / 2)
init()
for i in range(int(input())):
	print(solve())


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()


q = int(input())

def check(num):
	ans = True
	while ans and num > 0:
		x = num % 3
		if x == 2:
			return False
		num = num // 3
	return True
for _ in range(q):
	n = int(input())
	while not check(n):
		n += 1
	print(n)


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)


import bisect
MAXP = 10
l = [0] * MAXP
for i in range(MAXP):
	l[i] = 3 ** i
s = set()
for b in range(1 << MAXP):
	tmp = 0
	for i in range(MAXP):
		if b >> i & 1:
			tmp += l[i]
	s.add(tmp)
goodlist = sorted(list(s))
q = int(input())
for i in range(q):
	n = int(input())
	ans = goodlist[bisect.bisect_left(goodlist, n)]
	print(ans)


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)


from math import *

def test(nb, indice):
	global mini, a
	if indice >= len(puiss):
		if nb >= a:
			mini = min(mini, nb)
		return
	test(nb + puiss[indice], indice + 1)
	test(nb, indice + 1)
puiss = [3 ** i for i in range(100) if 3 ** i <= 100005]
q = int(input())
for i in range(q):
	a = int(input())
	mini = float('inf')
	test(0, 0)
	print(mini)


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)


def isgood(n):
	while n > 0:
		if n % 3 > 1:
			return False
		n //= 3
	return True
q = int(input())
for _ in range(q):
	n = int(input())
	while not isgood(n):
		n += 1
	print(n)


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)


for _ in range(int(input())):
	n = int(input())
	while 1:
		cur = n
		f = 1
		while cur > 0:
			if f and cur % 3 == 2:
				f = 0
			cur = cur // 3
		if f:
			break
		n = n + 1
	print(n)


def eval(num):
	if num >= 0:
		return chr(num + ord('0'))

def convertbase3(n):
	index = 0
	string = ''
	while n > 0:
		string += eval(n % 3)
		n = int(n / 3)
	string = string[::-1]
	if n == 1:
		return '1'
	elif n == 2:
		return '02'
	else:
		return string
for _ in range(int(input())):
	n = int(input())
	s = convertbase3(n)
	flg = 0
	for i in s:
		if i == '2':
			flg = 1
	if flg != 1:
		print(n)
	else:
		l = list(s)
		indx = -1
		for i in range(0, len(l)):
			if l[i] == '2':
				indx = i
				break
		flg = 0
		indx2 = len(l)
		for i in range(indx - 1, -1, -1):
			if l[i] == '0':
				l[i] = '1'
				flg = 1
				indx2 = i
				break
		for i in range(min(indx2 + 1, indx), len(l)):
			l[i] = '0'
		if flg == 1:
			ansstr = ''
			for i in l:
				ansstr += i
			print(int(ansstr, 3))
		else:
			ans = '1' + '0' * len(l)
			print(int(ans, 3))


t = int(input())
for tt in range(t):
	n = int(input())
	rem = n
	a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
	while rem > 0:
		i = 0
		while 3 ** i <= rem:
			i += 1
		i -= 1
		if 2 * 3 ** i <= rem:
			a[i] = 2
			rem -= 2 * 3 ** i
		else:
			a[i] = 1
			rem -= 3 ** i
	l = len(a)
	k = -1
	i = l - 1
	while i >= 0:
		if a[i] == 2:
			k = i
			break
		i -= 1
	if k == -1:
		s = 0
		for i in range(12):
			s += a[i] * 3 ** i
		print(s)
	else:
		if k > 0:
			for i in range(k):
				a[i] = 0
		while a[k] != 0:
			a[k] = 0
			k += 1
		a[k] = 1
		s = 0
		for i in range(12):
			s += a[i] * 3 ** i
		print(s)


import os
import sys
from io import BytesIO, IOBase

def nxt(n):
	a = []
	while n:
		a.append(n % 3)
		n //= 3
	a.append(0)
	a.append(0)
	a = a[::-1]
	for i in range(len(a)):
		if a[i] < 2:
			continue
		for j in range(i - 1):
			if a[i - j - 1] == 1:
				continue
			k = i - j - 1
			a[k] = 1
			a = a[:k + 1] + [0] * (len(a) - k - 1)
			break
		break
	n = 0
	for x in a:
		n = n * 3 + x
	return n

def main():
	n = 0
	a = [0]
	while n <= 10000:
		n = nxt(n + 1)
		a = a + [n]
	from bisect import bisect_left as lb
	for _ in range(int(input())):
		n = int(input())
		n = lb(a, n)
		print(a[n])
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()


q = int(input())

def getAllCombinations(object_list):
	uniq_objs = set(object_list)
	combinations = []
	for obj in uniq_objs:
		for i in range(0, len(combinations)):
			combinations.append(combinations[i] + obj)
		combinations.append(obj)
	return combinations
power3 = [pow(3, i) for i in range(10)]
combs = sorted(getAllCombinations(power3))

def findElement(n):
	for r in combs:
		if r >= n:
			return r
for k in range(q):
	n = int(input())
	print(findElement(n))


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)


ans = [0, 1, 3, 4, 9, 10, 12, 13, 27, 28, 30, 31, 36, 37, 39, 40, 81, 82, 84, 85, 90, 91, 93, 94, 108, 109, 111, 112, 117, 118, 120, 121, 243, 244, 246, 247, 252, 253, 255, 256, 270, 271, 273, 274, 279, 280, 282, 283, 324, 325, 327, 328, 333, 334, 336, 337, 351, 352, 354, 355, 360, 361, 363, 364, 729, 730, 732, 733, 738, 739, 741, 742, 756, 757, 759, 760, 765, 766, 768, 769, 810, 811, 813, 814, 819, 820, 822, 823, 837, 838, 840, 841, 846, 847, 849, 850, 972, 973, 975, 976, 981, 982, 984, 985, 999, 1000, 1002, 1003, 1008, 1009, 1011, 1012, 1053, 1054, 1056, 1057, 1062, 1063, 1065, 1066, 1080, 1081, 1083, 1084, 1089, 1090, 1092, 1093, 2187, 2188, 2190, 2191, 2196, 2197, 2199, 2200, 2214, 2215, 2217, 2218, 2223, 2224, 2226, 2227, 2268, 2269, 2271, 2272, 2277, 2278, 2280, 2281, 2295, 2296, 2298, 2299, 2304, 2305, 2307, 2308, 2430, 2431, 2433, 2434, 2439, 2440, 2442, 2443, 2457, 2458, 2460, 2461, 2466, 2467, 2469, 2470, 2511, 2512, 2514, 2515, 2520, 2521, 2523, 2524, 2538, 2539, 2541, 2542, 2547, 2548, 2550, 2551, 2916, 2917, 2919, 2920, 2925, 2926, 2928, 2929, 2943, 2944, 2946, 2947, 2952, 2953, 2955, 2956, 2997, 2998, 3000, 3001, 3006, 3007, 3009, 3010, 3024, 3025, 3027, 3028, 3033, 3034, 3036, 3037, 3159, 3160, 3162, 3163, 3168, 3169, 3171, 3172, 3186, 3187, 3189, 3190, 3195, 3196, 3198, 3199, 3240, 3241, 3243, 3244, 3249, 3250, 3252, 3253, 3267, 3268, 3270, 3271, 3276, 3277, 3279, 3280, 6561, 6562, 6564, 6565, 6570, 6571, 6573, 6574, 6588, 6589, 6591, 6592, 6597, 6598, 6600, 6601, 6642, 6643, 6645, 6646, 6651, 6652, 6654, 6655, 6669, 6670, 6672, 6673, 6678, 6679, 6681, 6682, 6804, 6805, 6807, 6808, 6813, 6814, 6816, 6817, 6831, 6832, 6834, 6835, 6840, 6841, 6843, 6844, 6885, 6886, 6888, 6889, 6894, 6895, 6897, 6898, 6912, 6913, 6915, 6916, 6921, 6922, 6924, 6925, 7290, 7291, 7293, 7294, 7299, 7300, 7302, 7303, 7317, 7318, 7320, 7321, 7326, 7327, 7329, 7330, 7371, 7372, 7374, 7375, 7380, 7381, 7383, 7384, 7398, 7399, 7401, 7402, 7407, 7408, 7410, 7411, 7533, 7534, 7536, 7537, 7542, 7543, 7545, 7546, 7560, 7561, 7563, 7564, 7569, 7570, 7572, 7573, 7614, 7615, 7617, 7618, 7623, 7624, 7626, 7627, 7641, 7642, 7644, 7645, 7650, 7651, 7653, 7654, 8748, 8749, 8751, 8752, 8757, 8758, 8760, 8761, 8775, 8776, 8778, 8779, 8784, 8785, 8787, 8788, 8829, 8830, 8832, 8833, 8838, 8839, 8841, 8842, 8856, 8857, 8859, 8860, 8865, 8866, 8868, 8869, 8991, 8992, 8994, 8995, 9000, 9001, 9003, 9004, 9018, 9019, 9021, 9022, 9027, 9028, 9030, 9031, 9072, 9073, 9075, 9076, 9081, 9082, 9084, 9085, 9099, 9100, 9102, 9103, 9108, 9109, 9111, 9112, 9477, 9478, 9480, 9481, 9486, 9487, 9489, 9490, 9504, 9505, 9507, 9508, 9513, 9514, 9516, 9517, 9558, 9559, 9561, 9562, 9567, 9568, 9570, 9571, 9585, 9586, 9588, 9589, 9594, 9595, 9597, 9598, 9720, 9721, 9723, 9724, 9729, 9730, 9732, 9733, 9747, 9748, 9750, 9751, 9756, 9757, 9759, 9760, 9801, 9802, 9804, 9805, 9810, 9811, 9813, 9814, 9828, 9829, 9831, 9832, 9837, 9838, 9840, 9841, 19683, 19684, 19686, 19687, 19692, 19693, 19695, 19696, 19710, 19711, 19713, 19714, 19719, 19720, 19722, 19723, 19764, 19765, 19767, 19768, 19773, 19774, 19776, 19777, 19791, 19792, 19794, 19795, 19800, 19801, 19803, 19804, 19926, 19927, 19929, 19930, 19935, 19936, 19938, 19939, 19953, 19954, 19956, 19957, 19962, 19963, 19965, 19966, 20007, 20008, 20010, 20011, 20016, 20017, 20019, 20020, 20034, 20035, 20037, 20038, 20043, 20044, 20046, 20047, 20412, 20413, 20415, 20416, 20421, 20422, 20424, 20425, 20439, 20440, 20442, 20443, 20448, 20449, 20451, 20452, 20493, 20494, 20496, 20497, 20502, 20503, 20505, 20506, 20520, 20521, 20523, 20524, 20529, 20530, 20532, 20533, 20655, 20656, 20658, 20659, 20664, 20665, 20667, 20668, 20682, 20683, 20685, 20686, 20691, 20692, 20694, 20695, 20736, 20737, 20739, 20740, 20745, 20746, 20748, 20749, 20763, 20764, 20766, 20767, 20772, 20773, 20775, 20776, 21870, 21871, 21873, 21874, 21879, 21880, 21882, 21883, 21897, 21898, 21900, 21901, 21906, 21907, 21909, 21910, 21951, 21952, 21954, 21955, 21960, 21961, 21963, 21964, 21978, 21979, 21981, 21982, 21987, 21988, 21990, 21991, 22113, 22114, 22116, 22117, 22122, 22123, 22125, 22126, 22140, 22141, 22143, 22144, 22149, 22150, 22152, 22153, 22194, 22195, 22197, 22198, 22203, 22204, 22206, 22207, 22221, 22222, 22224, 22225, 22230, 22231, 22233, 22234, 22599, 22600, 22602, 22603, 22608, 22609, 22611, 22612, 22626, 22627, 22629, 22630, 22635, 22636, 22638, 22639, 22680, 22681, 22683, 22684, 22689, 22690, 22692, 22693, 22707, 22708, 22710, 22711, 22716, 22717, 22719, 22720, 22842, 22843, 22845, 22846, 22851, 22852, 22854, 22855, 22869, 22870, 22872, 22873, 22878, 22879, 22881, 22882, 22923, 22924, 22926, 22927, 22932, 22933, 22935, 22936, 22950, 22951, 22953, 22954, 22959, 22960, 22962, 22963, 26244, 26245, 26247, 26248, 26253, 26254, 26256, 26257, 26271, 26272, 26274, 26275, 26280, 26281, 26283, 26284, 26325, 26326, 26328, 26329, 26334, 26335, 26337, 26338, 26352, 26353, 26355, 26356, 26361, 26362, 26364, 26365, 26487, 26488, 26490, 26491, 26496, 26497, 26499, 26500, 26514, 26515, 26517, 26518, 26523, 26524, 26526, 26527, 26568, 26569, 26571, 26572, 26577, 26578, 26580, 26581, 26595, 26596, 26598, 26599, 26604, 26605, 26607, 26608, 26973, 26974, 26976, 26977, 26982, 26983, 26985, 26986, 27000, 27001, 27003, 27004, 27009, 27010, 27012, 27013, 27054, 27055, 27057, 27058, 27063, 27064, 27066, 27067, 27081, 27082, 27084, 27085, 27090, 27091, 27093, 27094, 27216, 27217, 27219, 27220, 27225, 27226, 27228, 27229, 27243, 27244, 27246, 27247, 27252, 27253, 27255, 27256, 27297, 27298, 27300, 27301, 27306, 27307, 27309, 27310, 27324, 27325, 27327, 27328, 27333, 27334, 27336, 27337, 28431, 28432, 28434, 28435, 28440, 28441, 28443, 28444, 28458, 28459, 28461, 28462, 28467, 28468, 28470, 28471, 28512, 28513, 28515, 28516, 28521, 28522, 28524, 28525, 28539, 28540, 28542, 28543, 28548, 28549, 28551, 28552, 28674, 28675, 28677, 28678, 28683, 28684, 28686, 28687, 28701, 28702, 28704, 28705, 28710, 28711, 28713, 28714, 28755, 28756, 28758, 28759, 28764, 28765, 28767, 28768, 28782, 28783, 28785, 28786, 28791, 28792, 28794, 28795, 29160, 29161, 29163, 29164, 29169, 29170, 29172, 29173, 29187, 29188, 29190, 29191, 29196, 29197, 29199, 29200, 29241, 29242, 29244, 29245, 29250, 29251, 29253, 29254, 29268, 29269, 29271, 29272, 29277, 29278, 29280, 29281, 29403, 29404, 29406, 29407, 29412, 29413, 29415, 29416, 29430, 29431, 29433, 29434, 29439, 29440, 29442, 29443, 29484, 29485, 29487, 29488, 29493, 29494, 29496, 29497, 29511, 29512, 29514, 29515, 29520, 29521, 29523, 29524]
q = int(input())
for i in range(q):
	n = int(input())
	for j in range(len(ans)):
		if ans[j] >= n:
			print(ans[j])
			break


import sys
q = int(input())

def base3(num):
	ret = ''
	while num != 0:
		ret += str(num % 3)
		num = int(num / 3)
	ret += '0'
	return ret[::-1]
for qq in range(q):
	num = int(input())
	snum = base3(num)
	slen = len(snum)
	i = 0
	cnt = 0
	ans = ''
	while True:
		cnt += 1
		if i == slen or snum[i] == '0':
			ans += '1' * (cnt - 1) + '0'
			cnt = 0
			if i == slen:
				break
		elif snum[i] == '2':
			ans = ans[:-1] + '1' + '0' * (cnt + slen - i)
			break
			cnt = 0
		i += 1
	ans = ans[:-1]
	print(int(ans, 3))


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 bisect
t = int(input())
tmp_ans = [0] * 100
for i in range(100):
	tmp_ans[i] = 3 ** i
ans = []
for i in range(18):
	tmp = ans[0:]
	for j in tmp:
		ans.append(j + tmp_ans[i])
	ans.append(tmp_ans[i])
ans = sorted(ans)
for _ in range(t):
	n = int(input())
	ind = bisect.bisect_left(ans, n)
	print(ans[ind])


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()


from sys import stdin
from itertools import product

def main():
	bb = bytearray((0,)) * 29525
	for t in product(*[(3 ** i, 0) for i in range(10)]):
		bb[sum(t)] = 1
	data = list(map(int, stdin.read().splitlines()[1:]))
	for (i, x) in enumerate(data):
		data[i] = str(bb.find(1, x))
	print('\n'.join(map(str, data)))
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))


import math
q = int(input())
for i in range(q):
	n = int(input())
	original = n
	i = 0
	maxi = math.floor(math.log(n, 3))
	multiple = []
	used = []
	for i in range(maxi, -1, -1):
		multiple.append(math.floor(math.pow(3, i)))
		used.append(0)
	found = False
	pplused = 0
	for i in range(len(multiple)):
		if n == multiple[i]:
			found = True
			break
		elif n > multiple[i]:
			n = n - multiple[i]
			pplused += multiple[i]
			used[i] = 1
	if found == True:
		print(original)
	else:
		totalsum = sum(multiple)
		if totalsum < original:
			x = math.ceil(math.log(original, 3))
			print(int(math.pow(3, x)))
		else:
			for i in range(len(multiple) - 1, -1, -1):
				if used[i] == 1:
					pplused -= multiple[i]
				elif used[i] == 0:
					print(pplused + multiple[i])
					found = True
					break
			if found == False:
				x = math.ceil(math.log(original, 3))
				print(int(math.pow(3, x)))


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)


a = []
for i in range(10):
	a.append(3 ** i)
b = []
for j in range(11, 21):
	b.append(3 ** j)

def subsum(a, c, j, s, n):
	for i in range(j, n):
		s += a[i]
		c.append(s)
		subsum(a, c, i + 1, s - a[i], n)
c = []
subsum(a, c, 0, 0, 10)
d = []
subsum(b, d, 0, 0, 10)
d.append(0)
d.sort()

def binary_search(d, k, n):
	start = 0
	end = len(d) - 1
	mini = 9 * 10 ** 18
	while start <= end:
		mid = (start + end) // 2
		if d[mid] + k == n:
			return n
		elif d[mid] + k >= n:
			mini = min(mini, d[mid] + k)
			end = mid - 1
		else:
			start = mid + 1
	return mini
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	mini = 9 * 10 ** 18
	flag = 0
	u = len(c)
	for i in range(u):
		s = binary_search(d, c[i], n)
		if s == n:
			print(n)
			flag = 1
			break
		else:
			mini = min(s, mini)
	if flag == 0:
		print(mini)


for u in range(int(input())):
	n = int(input())
	x = n
	while 1:
		x = n
		f = 0
		while x > 0:
			r = x % 3
			if r == 2:
				f = 1
				break
			x = x // 3
		if f == 0:
			print(n)
			break
		else:
			n = n + 1


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 *
t = int(input())
a = []
k = 1
for i in range(9):
	s = len(a)
	a.append(k)
	for j in range(s):
		a.append(a[j] + k)
	k *= 3
a.append(k)
for y in range(t):
	n = int(input())
	for i in a:
		if i >= n:
			print(i)
			break


def all_subsets(myset):
	subset = [None] * len(myset)
	helper(myset, subset, 0)

def helper(myset, subset, i):
	if i == len(myset):
		print_sub(subset)
	else:
		subset[i] = None
		helper(myset, subset, i + 1)
		subset[i] = myset[i]
		helper(myset, subset, i + 1)

def print_sub(subset):
	subs = []
	for i in subset:
		if i != None:
			subs.append(i)
	this.append(sum(subs))
thresh = [3 ** i for i in range(10)]
this = []
all_subsets(thresh)
for _ in range(int(input())):
	n = int(input())
	ans = 100000
	for i in this:
		if i >= n:
			if i < ans:
				ans = i
	print(ans)


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)


import bisect

def D2T(num, a):
	if num > 2:
		D2T(num // 3, a)
	a.append(str(num % 3))
	return ''.join(a)
d = []
for i in range(1, 2 * 10 ** 4 + 1):
	if '2' not in D2T(i, []):
		d.append(i)
for _ in range(int(input())):
	n = int(input())
	ans = d[bisect.bisect_left(d, n)]
	print(ans)


def find_least_bit(num):
	bits = [0] * 9
	for i in range(8, -1, -1):
		temp = pow(3, i)
		if temp < num:
			num -= temp
			bits[i] = '1'
		else:
			bits[i] = '0'
	bits.reverse()
	return ''.join(bits)

def third_bit_to_num(s):
	result = 0
	for i in range(len(s)):
		result = result * 3 + int(s[i])
	return result

def next_bit(s):
	remember = (int(s[-1]) + 1) // 2
	result = str((int(s[-1]) + 1) % 2)
	for i in range(len(s) - 2, -1, -1):
		bit = (int(s[i]) + remember) % 2
		remember = (int(s[i]) + remember) // 2
		result = str(bit) + result
	if remember:
		result = '1' + result
	return result
q = int(input())
for i in range(q):
	n = int(input())
	smallest = find_least_bit(n)
	print(third_bit_to_num(next_bit(smallest)))


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)


import sys
input = sys.stdin.readline
import bisect

def main():
	q = int(input())
	three_list = [3 ** x for x in range(10)]
	good_list = [0] * 2 ** 10
	for i in range(2 ** 10):
		for j in range(10):
			if i >> j & 1:
				good_list[i] += three_list[j]
	s_good_list = sorted(good_list)
	for _ in range(q):
		N = int(input())
		i = bisect.bisect_left(s_good_list, N)
		print(s_good_list[i])
main()


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))


import itertools
a = [0, 1, 2, 3, 4, 5, 6, 7, 8]
b = []
gdnumbers = []
for i in range(1, 10):
	b = list(itertools.combinations(a, i))
	for j in b:
		m = list(j)
		s = 0
		for k in m:
			s = s + 3 ** k
		gdnumbers.append(s)
gdnumbers.sort()
q = int(input(''))
n = []
for i in range(q):
	n.append(int(input('')))
for i in n:
	if i > gdnumbers[len(gdnumbers) - 1]:
		print(3 ** 9)
		continue
	for j in range(len(gdnumbers)):
		if gdnumbers[j] >= i:
			print(gdnumbers[j])
			break


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 os
import sys
from io import BytesIO, IOBase
from bisect import bisect_left as bl
import math

def main():
	a = [3 ** x for x in range(10)]
	ans = []
	for x in range(1, 1 << 10):
		sm = 0
		for y in range(10):
			if 1 << y & x != 0:
				sm += a[y]
		ans.append(sm)
	ans.sort()
	for x in range(int(input())):
		n = int(input())
		print(ans[bl(ans, n)])
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()


ans = []
for i in range(20000):
	y = 3 ** 9
	x = 0
	n = 1
	z = i
	while n:
		if z - y >= 0:
			z -= y
		y //= 3
		n = 1
		if z == 0:
			x = 1
		if y < 1:
			n = 0
	if x:
		ans.append(i)
we = int(input())
for w in range(we):
	a = int(input())
	for mem in range(len(ans)):
		if ans[mem] >= a:
			print(ans[mem])
			break


from itertools import combinations
z = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683]
a = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683]
for i in range(2, 10):
	for j in combinations(z, i):
		a.append(sum(j))
a = sorted(a)
q = int(input())
for i in range(q):
	n = int(input())
	for j in a:
		if j >= n:
			print(j)
			break


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)


def v(n):
	ans = ''
	while n > 0:
		ans += str(n % 3)
		if n % 3 == 2:
			return '2'
		n //= 3
	return ans
for _ in range(int(input())):
	n = int(input())
	flag = True
	while flag:
		num = v(n)
		if num.find('2') == -1:
			print(n)
			flag = False
		else:
			n += 1


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 mapit():
	temp = list(map(int, input().split()))
	return temp
arr = [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, 12157665459056928801]
ans = []
for j in range(1, 10001):
	nm = j
	for i in range(len(arr) - 1, -1, -1):
		if arr[i] <= nm:
			nm -= arr[i]
	if nm == 0:
		ans.append(j)
ans.append(19683)
import bisect

def solution():
	global ans
	n = int(input())
	print(ans[bisect.bisect_left(ans, n)])
	return
t = int(input())
while t:
	t -= 1
	solution()


n = int(input())
import math
klist = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683]
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 c - d >= math.log(1.5, 3):
			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)


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))


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
	while m < n:
		m = d(t)
		t += 1
	print(m)


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)


import math

def main():
	queries = int(input())
	powers_of_3 = []
	possible_results = [3 ** 9]
	for i in range(0, 9):
		powers_of_3.append(3 ** i)
	for i in range(2 ** 9):
		binary_list = [int(x) for x in bin(i)[2:]]
		zero_list_size = 9 - len(binary_list)
		zero_list = [0] * zero_list_size
		zero_list.extend(binary_list)
		current_value = [a * b for (a, b) in zip(zero_list, powers_of_3)]
		possible_results.append(sum(current_value))
	possible_results.sort()
	for _ in range(queries):
		number = int(input())
		for possible_number in possible_results:
			if number <= possible_number:
				print(possible_number)
				break
main()


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)


from bisect import bisect_left
from itertools import product
NUMS = [sum((X[i] * 3 ** i for i in range(10))) for X in product(range(2), repeat=10)]
NUMS.sort()
for _ in range(int(input())):
	print(NUMS[bisect_left(NUMS, int(input()))])


def foo(N):
	possible = [0]
	pow = 0
	while True:
		val = 3 ** pow
		temp = []
		for p in possible:
			new = p + val
			temp.append(new)
			if new >= N:
				return new
		possible.extend(temp)
		pow += 1
T = int(input())
for i in range(T):
	N = int(input())
	print(foo(N))


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 io
import os
import sys
from atexit import register
import random
import math
import itertools
DEBUG = False
STRESSTEST = False
if not DEBUG:
	input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
sys.stdout = io.BytesIO()
register(lambda : os.write(1, sys.stdout.getvalue()))
tokens = []
tokens_next = 0

def nextStr():
	global tokens, tokens_next
	while tokens_next >= len(tokens):
		tokens = input().split()
		tokens_next = 0
	tokens_next += 1
	if type(tokens[tokens_next - 1]) == str:
		return tokens[tokens_next - 1]
	return tokens[tokens_next - 1].decode()

def nextInt():
	return int(nextStr())

def nextIntArr(n):
	return [nextInt() for i in range(n)]

def print(*argv, end='\n'):
	for arg in argv:
		sys.stdout.write((str(arg) + ' ').encode())
	sys.stdout.write(end.encode())

def genTestCase():
	raise NotImplementedError

def bruteforce(a):
	raise NotImplementedError

def doStressTest():
	while True:
		curTest = genTestCase()
		mySoln = solve(curTest)
		bruteforceSoln = bruteforce(curTest)
		if mySoln != bruteforceSoln:
			print('### Found case ###')
			print(curTest)
			print(f'{mySoln} should have been: {bruteforceSoln}')
			return

def toTernary(n):
	res = []
	while n > 0:
		res.append(n % 3)
		n //= 3
	return list(reversed(res))

def solve(n):
	m = toTernary(n)
	m = list(reversed(m))
	twoPos = next((i for i in range(len(m) - 1, -1, -1) if m[i] == 2), -1)
	if twoPos == -1:
		return int(''.join(map(str, reversed(m))), 3)
	zeroPos = next((i for i in range(twoPos + 1, len(m)) if m[i] == 0), len(m))
	m[zeroPos:zeroPos + 1] = [1]
	m[:zeroPos] = [0] * len(m[:zeroPos])
	return int(''.join(map(str, reversed(m))), 3)
if not DEBUG and STRESSTEST:
	raise Exception('Wrong flags!')
if STRESSTEST:
	doStressTest()
else:
	q = nextInt()
	for _ in range(q):
		n = nextInt()
		print(solve(n))
sys.stdout.flush()


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()


all_numbers = []

def gera(n=0, soma=0, vetor=all_numbers):
	if n == 10:
		all_numbers.append(soma)
	else:
		gera(n + 1, soma + 3 ** n)
		gera(n + 1, soma)
gera()
all_numbers.sort()

def upper(x, l=0, r=len(all_numbers) - 1, vetor=all_numbers):
	if l > r:
		return l
	else:
		mid = (l + r) // 2
		if vetor[mid] == x:
			return mid
		elif vetor[mid] > x:
			return upper(x, l, mid - 1)
		else:
			return upper(x, mid + 1, r)
n = int(input())
for _ in range(n):
	x = int(input())
	print(all_numbers[upper(x)])


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()))


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
q = int(input())
arr = [to_tri(i) for i in range(20001)]
for i in range(q):
	n = int(input())
	l = list(map(lambda x: x < 2, arr[n]))
	if all(l):
		print(n)
		continue
	else:
		c = n
		while not all(l):
			c = c + 1
			l = map(lambda x: x < 2, arr[c])
		print(c)


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)))


n = int(input())
for i in range(n):
	number = int(input())
	for k in range(10):
		if 3 ** k >= number:
			closest_three = 3 ** k
			biggest_k = k
			break
	flag = False
	for j in range(number, closest_three):
		number_tracker = j
		for jj in reversed(range(biggest_k)):
			if j - 3 ** jj >= 0:
				j -= 3 ** jj
		if j == 0:
			flag = True
			print(number_tracker)
			break
	if not flag:
		print(closest_three)


def to_base_3(n):
	ans = []
	while n != 0:
		ans.append(n % 3)
		n = int(n / 3)
	ans.append(0)
	return ans

def to_base_10(b3):
	ans = 0
	rec = 1
	for d in b3:
		ans += d * rec
		rec *= 3
	return ans
q = int(input())
for _ in range(q):
	n = int(input())
	base_3 = to_base_3(n)
	if 2 not in base_3:
		print(n)
	else:
		base_3.reverse()
		ind = base_3.index(2)
		ind = len(base_3) - 1 - ind
		base_3.reverse()
		for i in range(len(base_3)):
			if i <= ind:
				base_3[i] = 0
			elif base_3[i] == 0:
				base_3[i] = 1
				break
			elif base_3[i] == 1:
				base_3[i] = 0
		print(to_base_10(base_3))


import itertools
LIMIT = 9
powers = [i for i in range(LIMIT)]
perms = []
items = []
numbers = []
for i in range(1, LIMIT + 1):
	perms += itertools.combinations(powers, i)
for i in perms:
	r = 0
	for j in i:
		r += pow(3, j)
	numbers.append(r)
numbers.append(3 ** 9)
numbers.sort()

def find(l, r, item):
	mid = l + (r - l) // 2
	if r >= l:
		if numbers[mid] == item:
			return item
		if numbers[mid] > item:
			return find(l, mid - 1, item)
		else:
			return find(mid + 1, r, item)
	else:
		return numbers[l]
q = int(input())
l_numbers = len(numbers)
for _ in range(q):
	n = int(input())
	print(find(0, l_numbers, n))


import bisect
l = []

def find_ge(x):
	i = bisect.bisect_left(l, x)
	if i != len(l):
		return l[i]

def b3(n):
	while n:
		(n, r) = divmod(n, 3)
		if r == 2:
			return False
	return True

def pre():
	for j in range(1, 19684):
		if b3(j):
			l.append(j)
pre()
q = int(input())
for i in range(q):
	n = int(input())
	print(find_ge(n))


def goodNum(n):
	pow = 1
	answer = 0
	while n:
		pow = pow * 3
		if n & 1:
			answer += pow
		n >>= 1
	return answer
numeros = []
for i in range(0, 260):
	num = goodNum(i)
	numeros.append(num)
	numeros.append(num + 1)
q = int(input())
for queries in range(q):
	n = int(input())
	for e in numeros:
		if e >= n:
			print(e)
			break


l = []
for i in range(0, 31):
	l.append(3 ** i)
l = l[::-1]
for _ in range(int(input())):
	n = int(input())
	s = sum(l)
	for i in l:
		if s - i >= n:
			s = s - i
	print(s)


x = [1]
for i in range(1, 10):
	y = pow(3, i)
	x.append(y)
	n = len(x)
	for j in range(n - 1):
		k = x[j] + y
		x.append(k)
for j in range(int(input())):
	n = int(input())
	y = len(x)
	for i in range(y):
		if x[i] >= n:
			break
	print(x[i])


l = [0] * 10
l[0] = 1
s = [0] * 10
s[0] = 0
for i in range(1, 10):
	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 ** 9
	cnt = 9
	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


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)


q = int(input())
for i in range(q):
	n = int(input())
	k = 1
	mas = [1]
	while mas[-1] < n:
		mas.append(3 ** k)
		f = len(mas) - 1
		for i in range(f - 1):
			mas.append(mas[f] + mas[i])
		s = 0
		for i in range(k + 1):
			s += 3 ** i
		mas.append(s)
		k += 1
	p = len(mas) - 1
	while mas[p] >= n:
		if p != 0:
			p -= 1
		else:
			p -= 1
			break
	print(mas[p + 1])


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)


from sys import *

def fun(n):
	p = [0 for i in range(n + 2)]
	index = 0
	x = n
	while x > 0:
		p[index] = x % 3
		x = x // 3
		index += 1
	idx = 0
	for i in range(len(p) - 1):
		if p[i] > 1:
			p[i] = 0
			p[i + 1] += 1
			for j in range(idx, i):
				p[j] = 0
			idx += 1
	j = len(p) - 1
	if p[j] >= 2:
		p[index] = 1
		index += 1
	ans = 0
	i = len(p) - 1
	while i >= 0:
		ans = ans * 3 + p[i]
		i -= 1
	print(ans)
t = int(stdin.readline())
while t > 0:
	n = int(stdin.readline())
	fun(n)
	t -= 1


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)


import sys

def readline():
	return input()
goods = []
for i in range(10000):
	n = 0
	for j in range(14):
		if i & 1 << j:
			n += 3 ** j
	goods.append(n)

def fun(n):
	for i in range(len(goods)):
		if goods[i] >= n:
			print(goods[i])
			break
q = int(readline())
for i in range(q):
	n = int(readline())
	fun(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))


import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)
from collections import *
from bisect import bisect_left as bl

def li():
	return [int(____) for ____ in input().rstrip('\n').split(' ')]

def val():
	return int(input().rstrip('\n'))

def st():
	return input().rstrip('\n')

def sttoli():
	return [int(i) for i in input().rstrip('\n')]
d = {}
for j in range(11):
	d[3 ** j] = 1
s = set()
for k in d:
	s2 = set()
	for p in s:
		s2.add(k + p)
	s2.add(k)
	s |= s2
s2 = s
s = sorted(list(s))
for _ in range(val()):
	n = val()
	if n in s:
		print(n)
	else:
		ind = bl(s, n)
		print(s[ind])


queries = int(input())
for q in range(queries):
	n = int(input())
	p = 9
	dp = [0] * p
	r = n
	for i in range(p)[::-1]:
		(dp[i], r) = divmod(r, 3 ** i)
	if all((i <= 1 for i in dp)):
		print(str(n))
	else:
		r = p
		while dp[r - 1] == 0:
			r -= 1
		l = r - 1
		while dp[l] < 2:
			l -= 1
		for i in range(l + 1):
			dp[i] = 0
		l += 1
		while l < r and dp[l] == 1:
			dp[l] = 0
			l += 1
		if l < r and dp[l] == 0:
			dp[l] = 1
			print(str(sum((dp[i] * 3 ** i for i in range(p)))))
		else:
			print(str(3 ** r))


from bisect import bisect_right
l = [1]
for i in range(1, 10):
	k = pow(3, i)
	l.append(k)
	l1 = len(l)
	for i in range(l1 - 1):
		s = l[i] + k
		l.append(s)
for i in range(int(input())):
	n = int(input())
	k = len(l)
	for i in range(k):
		if l[i] >= n:
			break
	print(l[i])


q = int(input())
while q:
	q -= 1
	n = int(input())
	good = [1]
	x = 1
	while 1:
		t = 3 ** x
		ans = []
		for i in good:
			ans.append(t + i)
		good.append(t)
		for i in ans:
			good.append(i)
		x += 1
		if max(good) >= n:
			break
	for i in good:
		if i >= n:
			print(i)
			break


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):
	while n > 0:
		if n % 3 == 2:
			return 0
		n = n // 3
	return 1
for _ in range(int(input())):
	n = int(inp())
	z = n % 3
	if bs(n) == 1:
		print(n)
	elif bs(n + 1) == 1:
		print(n + 1)
	elif bs(n + 2) == 1:
		print(n + 2)
	else:
		if z != 0:
			n = 3 * (n // 3 + 1)
		p = bs(n)
		while p != 1:
			n = n + 3
			p = bs(n)
			if p == 1:
				break
		print(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 math

def good_numbers(n: int) -> int:
	i = 1
	up_to_power_of_3 = math.ceil(math.log(n, 3))
	while True:
		acc = 0
		j = 0
		while j <= up_to_power_of_3:
			if i % 2 ** (j + 1) >= 2 ** j:
				acc += 3 ** j
			j += 1
		if acc >= n:
			return acc
		i += 1

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))


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()


T = int(input())
for _ in range(T):
	exp = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
	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 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)


import sys
import itertools
import math
import collections
from collections import Counter

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 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 ceil(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 dd():
	return collections.defaultdict(int)
w = [0] * 10001
p = []
for i in range(9):
	p.append(3 ** i)
c = 0
for i in range(1, len(p) + 1):
	for j in list(itertools.combinations(p, i)):
		c += 1
		if sum(j) <= 10000:
			w[sum(j)] = sum(j)
w[10000] = 19683
for i in range(9999, -1, -1):
	if w[i] == 0:
		w[i] = w[i + 1]
t = ii()
for i in range(t):
	n = ii()
	print(w[n])


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))


for _ in range(int(input())):
	n = int(input())
	while True:
		ok = True
		cur = n
		while cur > 0:
			if ok and cur % 3 == 2:
				ok = False
			cur = int(cur / 3)
		if ok:
			break
		n += 1
	print(n)


def pre(x):
	global ans
	a = 19683
	b = x
	while a >= 1:
		if b >= a:
			b -= a
		a //= 3
	if b == 0:
		ans[x] = True
ans = [False for x in range(20000)]
ans[1] = True
ans[3] = True
for i in range(4, 20000):
	pre(i)
answ = [1 for x in range(10001)]
x = 2
j = 3
while x < 10001:
	if x > j:
		j = x
	while not ans[j]:
		j += 1
	answ[x] = j
	x += 1
q = int(input())
while q > 0:
	print(answ[int(input())])
	q -= 1


mod = 10 ** 9 + 7
import sys
from sys import stdin, stdout
from bisect import bisect_left
from itertools import combinations
li = [3 ** i for i in range(10)]
s = {}
x = [0] * 29524
for i in range(1, 10):
	comb = combinations(li, i)
	for j in list(comb):
		x[sum(j)] = sum(j)
prev = 29523
for i in range(29523, -1, -1):
	if x[i] == 0:
		x[i] += prev
	else:
		prev = x[i]
for _ in range(int(input())):
	n = int(input())
	print(x[n])


q = int(input())
while q > 0:
	n = int(input())
	x = 0
	k = 0
	while n >= x:
		x += 3 ** k
		k += 1
	k -= 1
	print()
	while x >= n and k >= 0:
		if x - 3 ** k >= n:
			x -= 3 ** k
		k -= 1
	print(x)
	q -= 1


def numberToBase(n, b):
	if n == 0:
		return [0]
	digits = []
	while n:
		digits.append(int(n % b))
		n //= b
	s = digits[::-1]
	for i in s:
		if i == 2:
			return False
	return True
d = dict()
for i in range(int(input())):
	n = int(input())
	x = n
	ans = n
	if n not in d.keys():
		while numberToBase(n, 3) == False:
			n += 1
			ans = n
		d[x] = n
	print(d[x])


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)


import bisect

def subsetSums(arr, l, r, sum=0):
	global pos
	if l > r:
		return
	if sum > 0:
		pos.append(sum)
	subsetSums(arr, l + 1, r, sum + arr[l])
	subsetSums(arr, l + 1, r, sum)
pos = []
three = [1]
for i in range(1, 11):
	three.append(3 ** i)
three.sort()
subsetSums(three, 0, len(three) - 1)
pos = list(sorted(set(pos)))
q = int(input())
while q > 0:
	q -= 1
	n = int(input())
	print(pos[bisect.bisect_left(pos, n)])


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)


v = []
i = 0
while True:
	st = bin(i).replace('0b', '')
	k = num = 0
	for j in range(len(st) - 1, -1, -1):
		num += int(st[j]) * pow(3, k)
		k += 1
	if num > 100000:
		break
	v.append(num)
	i += 1
v.sort()
from bisect import bisect_left
for _ in range(int(input())):
	n = int(input())
	idx = bisect_left(v, n)
	print(v[idx])


from bisect import bisect_left
from sys import stdin

def main():
	input = lambda : stdin.readline()[:-1]
	Q = int(input())
	three = [3 ** i for i in range(10)]
	good = []
	for mask in range(1 << 10):
		sum_ = 0
		for i in range(10):
			if mask & 1 << i:
				sum_ += three[i]
		good.append(sum_)
	for _ in [0] * Q:
		N = int(input())
		i = bisect_left(good, N)
		print(good[i])
main()


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)


p = [3 ** i for i in range(20)]
p.reverse()
sp = sum(p)
for _ in range(int(input())):
	n = int(input())
	s = sp
	for i in p:
		if s - i >= n:
			s -= i
	print(s)


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()


from sys import stdin, stdout
MAX = 9
subset = []
numbers = []

def num(l):
	r = 0
	for x in l:
		r += pow(3, x)
	return r

def search(k):
	global MAX
	global subset
	if k == MAX + 1:
		if len(subset) != 0:
			numbers.append(num(subset))
	else:
		subset.append(k)
		search(k + 1)
		subset.pop()
		search(k + 1)
search(0)
numbers.sort()
t = int(stdin.readline().rstrip())
while t > 0:
	n = int(stdin.readline().rstrip())
	for m in numbers:
		if n <= m:
			stdout.write(str(m) + '\n')
			break
	t -= 1


q = int(input())
n = [int(input()) for _ in range(q)]
a = [3 ** i for i in range(10)]
ans = []
for i in range(q):
	c = []
	for j in range(2 ** 10):
		b = 0
		for k in range(10):
			if j >> k & 1:
				b += a[k]
		if b >= n[i]:
			c.append(b)
	c.sort()
	ans.append(c[0])
for i in range(q):
	print(ans[i])


from itertools import combinations
a3 = []
n = 1
while n <= 40000:
	a3.append(n)
	n *= 3
q = int(input())
for _ in range(q):
	delta = 100000
	n = int(input())
	for size in range(1, len(a3)):
		for c in combinations(a3, r=size):
			_sum = sum(c)
			if _sum - n < delta and _sum - n >= 0:
				delta = _sum - n
				res = _sum
	print(res)


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()


def base3(n):
	ans = 0
	i = 0
	flag = True
	while n != 0:
		ans += n % 3 * 10 ** i
		if n % 3 == 2:
			flag = False
			break
		n = n // 3
		i += 1
	return flag
q = int(input())
for i in range(q):
	n = int(input())
	while True:
		if base3(n):
			print(n)
			break
		n += 1


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 bisect
goodNumbers = set()
powers = [3 ** x for x in range(10)]

def gen():
	mask = (1 << 10) - 1
	while mask:
		temp = mask
		num = 0
		for x in range(10):
			if temp & 1 << x:
				num += powers[x]
		goodNumbers.add(num)
		mask -= 1
gen()
goodNumbers = sorted(list(goodNumbers))
q = int(input())
for _ in range(q):
	n = int(input())
	i = bisect.bisect_left(goodNumbers, n)
	print(goodNumbers[i])


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()


def mi():
	return map(int, input().split())
mod = 10 ** 9 + 7
from bisect import bisect_right
p = [3 ** i for i in range(10)]
poss = set()
for i in range(1 << 10):
	s = 0
	for j in range(10):
		if i & 1 << j:
			s += p[j]
	poss.add(s)
poss = sorted(list(poss))
for _ in range(int(input())):
	n = int(input()) - 1
	print(poss[bisect_right(poss, n)])


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)


def up_r(r, n):
	if r[n] == 0:
		r[n] = 1
	else:
		r[n] = 0
		up_r(r, n + 1)

def cont(r):
	s = 0
	p = 1
	for i in range(0, 20):
		if r[i]:
			s += p
		p *= 3
	return s
q = int(input())
for i in range(0, q):
	n = int(input())
	r = [0 for i in range(0, 20)]
	m = 0
	while m < n:
		up_r(r, 0)
		m = cont(r)
	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
input = sys.stdin.buffer.readline
N = int(input())
dp = [0] * (2 * 10 ** 4 + 1)
t = []
dp[1] = 1
for i in range(13):
	if pow(3, i) <= 2 * 10 ** 4:
		dp[pow(3, i)] = 1
		t.append(pow(3, i))
for i in t:
	for j in range(i):
		if dp[i] == 0:
			break
		if i + j > 2 * 10 ** 4:
			break
		if dp[j] == 1:
			dp[i + j] = 1
for _ in range(N):
	q = int(input())
	while dp[q] != 1:
		q += 1
	print(q)


t = int(input())
for _ in range(t):
	n = int(input())
	while True:
		ok = True
		o = n
		while o > 0:
			if ok and o % 3 == 2:
				ok = False
			o = int(o / 3)
		if ok:
			break
		else:
			n += 1
	print(n)


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)


k = [1]
for i in range(1, 10):
	t = pow(3, i)
	k.append(t)
	r = len(k)
	for i in range(r - 1):
		v = k[i] + t
		k.append(v)
for i in range(int(input())):
	m = int(input())
	t = len(k)
	for i in range(t):
		if k[i] >= m:
			break
	print(k[i])


import sys
import math

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

def three(n):
	while n > 0:
		s = n % 3
		n //= 3
		if s == 2:
			return False
	return True
test_case = int(input())
for _ in range(test_case):
	n = int(input())
	while not three(n):
		n += 1
	print(n)


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)


from sys import stdin
from collections import deque, Counter
import sys
import math
import operator
import random
from fractions import Fraction
import functools
nums = [pow(3, i) for i in range(10)]
pcx = []
s = 0
for i in range(1 << len(nums)):
	for j in range(len(nums)):
		if i & 1 << j:
			s = s + nums[j]
	pcx.append(s)
	s = 0
pcx.sort()
for _ in range(int(input())):
	n = int(input())
	i = 0
	while n > pcx[i]:
		i += 1
	print(pcx[i])


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


import bisect
F = set()
F.add(1)
for i in range(20000):
	if i % 3 == 0 and i // 3 in F:
		F.add(i)
	if i % 3 == 1 and i - 1 in F:
		F.add(i)
F = sorted(list(F))
q = int(input())
for _ in range(q):
	n = int(input())
	print(F[bisect.bisect_left(F, n)])


import re

def read(t=int):
	return list(map(t, input().strip().split(' ')))
data = [0]
for i in range(11):
	temp = data[:]
	base = 3 ** i
	for j in data:
		temp.append(base + j)
	data = temp
data = sorted(data)
q = read()[0]
while q > 0:
	q -= 1
	n = read()[0]
	for j in data:
		if j >= n:
			print(j)
			break


a = []
for i in range(30):
	a.append(3 ** i)
a.reverse()
s = sum(a)
for q in range(int(input())):
	n = int(input())
	res = s
	for j in range(30):
		if res - a[j] >= n:
			res = res - a[j]
	print(res)


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 A(n):
	return 2 * int(format(n - 1, 'b'), 3)
a = [0] * 100001
for i in range(1, 100000, 1):
	a[i] = int(A(i) / 2)
a = sorted(a)
for _ in range(int(input())):
	n = int(input())
	for k in a:
		if k >= n:
			print(k)
			break


def ternary(n):
	while n:
		if n % 3 == 2:
			return 0
		n //= 3
	return 1
for _ in range(int(input())):
	n = int(input())
	if ternary(n):
		print(n)
	else:
		while ternary(n) != 1:
			n += 1
		print(n)


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)


from sys import stdin
input = lambda : stdin.readline().rstrip('\r\n')
input_a = lambda fun: map(fun, stdin.readline().split())
a = []
for i in range(10):
	p = 3 ** i
	sums = [p + x for x in a]
	a.append(p)
	a.extend(sums)

def read():
	return int(input())

def solve(n):
	(i1, i2) = (0, len(a) - 1)
	while i2 - i1 > 1:
		m = (i1 + i2) // 2
		if n < a[m]:
			i2 = m
		else:
			i1 = m
	return a[i1] if a[i1] == n else a[i1 + 1]
for t in range(int(input())):
	result = solve(read())
	print(result)


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))


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
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:
		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
		while 2 in t:
			p = t.index(2)
			add_my_bit(t, p)
		v = len(t)
		if u < v:
			k = k + 3 ** (v - 1)
		else:
			for j in range(len(t)):
				k = k + 3 ** 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:
		k = n
	print(k)


from fractions import gcd
from itertools import combinations, permutations, accumulate, product
from collections import deque, defaultdict, Counter
import decimal
import re
import math
import bisect
import sys
sys.setrecursionlimit(10000000)
mod = 10 ** 9 + 7
from sys import stdin
readline = stdin.readline

def readInts():
	return list(map(int, readline().split()))

def readTuples():
	return tuple(map(int, readline().split()))

def I():
	return int(readline())
i = 0
s = set()
while i < 10:
	if i == 0:
		s.add(0)
		s.add(1)
		i += 1
		continue
	for c in list(s):
		s.add(c + 3 ** i)
	i += 1
for _ in range(I()):
	n = I()
	lis = sorted(list(s))
	print(lis[bisect.bisect_left(lis, n)])


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)


from bisect import bisect_right
from bisect import bisect_left

def BinarySearch(a, x):
	i = bisect_left(a, x)
	if i != len(a) and a[i] == x:
		return i
	else:
		return -1
ans = []

def subsetSums(arr, l, r, sum):
	if l > r:
		ans.append(sum)
		return
	subsetSums(arr, l + 1, r, sum + arr[l])
	subsetSums(arr, l + 1, r, sum)
t = int(input())
po = [3 ** i for i in range(0, 10)]
subsetSums(po, 0, len(po) - 1, 0)
ans.sort()
oo = []
for test in range(t):
	n = int(input())
	if BinarySearch(ans, n) != -1:
		oo.append(n)
		continue
	else:
		min_val = ans[bisect_right(ans, n)]
		oo.append(min_val)
for i in range(t):
	print(oo[i])


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)


from bisect import bisect_left as lower_bound

def preprocess():
	arr = [3 ** i for i in range(11)]
	mask = 0
	sums = []
	while mask < 1 << 11:
		mask1 = mask
		s = 0
		for i in range(11):
			if mask1 & 1:
				s += arr[i]
			mask1 >>= 1
		sums.append(s)
		mask += 1
	sums.sort()
	return sums

def main():
	sums = preprocess()
	t = int(input())
	for _ in range(t):
		n = int(input())
		pos = lower_bound(sums, n)
		print(sums[pos])
main()


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))


from itertools import chain, combinations

def powerset(iterable):
	s = list(iterable)
	return chain.from_iterable((combinations(s, r) for r in range(len(s) + 1)))
nq = int(input())
question_limit = 10 ** 4
base3exp = []
base = 3
exp = 0
raised = base ** exp
while raised <= question_limit:
	raised = base ** exp
	base3exp.append(raised)
	exp += 1
cumsum = [sum(base3exp[:i + 1]) for i in range(len(base3exp))]
power_set = powerset(base3exp)
possibles = [sum(tup) for tup in power_set]
for i in range(nq):
	n = int(input())
	for (i, summed) in enumerate(cumsum):
		if summed == n:
			print(n)
			break
		elif summed > n:
			if base3exp[i] > n:
				n = base3exp[i]
			while not n in possibles:
				n += 1
			print(n)
			break


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)


q = int(input())

def solve(n):
	if n == 0:
		return False
	while n:
		(n, r) = divmod(n, 3)
		if r == 2:
			return False
	return True
for i in range(q):
	n = int(input())
	m = n
	while True:
		if solve(m):
			print(m)
			break
		m = m + 1


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)


a = []
i = 0
while 3 ** i < 20000:
	a.append(3 ** i)
	i += 1
b = a.copy()
length = len(a)
for j in range(len(b)):
	flag = 0
	for k in range(length):
		if a[k] == b[j]:
			flag = a[k]
		elif a[k] >= 3 * flag:
			a.append(a[k] + b[j])
	a.sort()
	length = len(a)
ans = []
q = int(input())
for _ in range(q):
	n = int(input())
	for m in range(len(a)):
		if a[m] >= n:
			ans.append(a[m])
			break
print(*ans, sep='\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)


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


import sys
from math import *
input = sys.stdin.readline
RI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
rw = lambda : input().strip().split()
ls = lambda : list(input().strip())
from collections import defaultdict as df
import heapq
infinite = float('inf')
pre = []
bit = 1
for i in range(1, 2 ** 10):
	j = i
	temp = 0
	for k in range(10):
		if j % 2 == 1:
			temp += 3 ** k
		j //= 2
	pre.append(temp)
pre.sort()
t = int(input())
for i in range(t):
	n = int(input())
	for j in pre:
		if j >= n:
			print(j)
			break


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)


import sys

def main():

	def toStr(n, base):
		convertString = '012'
		if n < base:
			return convertString[n]
		else:
			return toStr(n // base, base) + convertString[n % base]
	k = []
	for i in range(100000):
		if '2' not in toStr(i, 3):
			k.append(i)
	for _ in range(int(input())):
		n = int(sys.stdin.readline())
		i = 0
		while n > k[i]:
			i = i + 1
		print(k[i])
main()


def f(n):
	if n > max_n:
		return
	n1 = 3 * n
	n2 = n1 + 1
	ans.append(n1)
	ans.append(n2)
	f(n1)
	f(n2)
n = 1
ans = [1]
max_n = 10000
f(n)
ans.sort()
for test in range(int(input())):
	n = int(input())
	for i in ans:
		if i >= n:
			print(i)
			break


import math
q = int(input())
for _ in range(q):
	n = int(input())
	k = math.log(n, 3)
	if k == int(k):
		print(n)
	elif (3 ** (int(k) + 1) - 1) / 2 < n:
		print(int(3 ** (int(k) + 1)))
	else:
		j = (3 ** (int(k) + 1) - 1) / 2
		for i in range(int(k) - 1, -1, -1):
			if j - 3 ** i >= n:
				j = j - 3 ** i
		print(int(j))


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


from bisect import bisect_left
for _ in range(int(input())):
	n = int(input())
	arr = []
	for i in range(10):
		curr = 3 ** i
		curr_sums = [curr + x for x in arr]
		arr.append(curr)
		arr.extend(curr_sums)
	i = bisect_left(arr, n)
	print(arr[i])


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


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

def reVal(num):
	if num >= 0 and num <= 9:
		return chr(num + ord('0'))
	else:
		return chr(num - 10 + ord('A'))

def strev(str):
	len = len(str)
	for i in range(int(len / 2)):
		temp = str[i]
		str[i] = str[len - i - 1]
		str[len - i - 1] = temp

def fromDeci(res, base, inputNum):
	index = 0
	while inputNum > 0:
		res += reVal(inputNum % base)
		inputNum = int(inputNum / base)
	res = res[::-1]
	return res
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	res = ''
	res = fromDeci(res, 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' and i > temp:
				ans = i
				break
		res = '0' * ans + '1' + res[ans + 1:]
		res = res[::-1]
		print(int(res, 3))


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))


from sys import stdin
import math
from collections import defaultdict

def eval(n):
	flag = True
	while n > 0 and flag:
		while n % 3 == 0:
			n //= 3
		n -= 1
		if n % 3 != 0:
			flag = False
	return flag
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	while 1:
		if eval(n):
			print(n)
			break
		n += 1


l1 = [1]
for i in range(9):
	l1.append(l1[-1] * 3)
l2 = [0]
for i in l1[:9]:
	for j in range(len(l2)):
		l2.append(i + l2[j])
l2.append(3 ** 9)
for _ in range(int(input())):
	n = int(input())
	for i in l2:
		if i >= n:
			print(i)
			break


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)


a = [1]
for _ in range(1, 10):
	p = pow(3, _)
	a1 = len(a)
	a.append(p)
	for i in range(a1):
		s = a[i] + p
		a.append(s)
for _ in range(int(input())):
	n = int(input())
	p = len(a)
	for i in range(p):
		if n <= a[i]:
			break
	print(a[i])


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)


import math
N = input()
N = int(N)
x = []
p = [pow(3, 0), pow(3, 1), pow(3, 2), pow(3, 3), pow(3, 4), pow(3, 5), pow(3, 6), pow(3, 7), pow(3, 8), pow(3, 9), pow(3, 10)]
for a in [0, 1]:
	for b in [0, 1]:
		for c in [0, 1]:
			for d in [0, 1]:
				for e in [0, 1]:
					for f in [0, 1]:
						for g in [0, 1]:
							for h in [0, 1]:
								for i in [0, 1]:
									for j in [0, 1]:
										x.append(a * p[0] + b * p[1] + c * p[2] + d * p[3] + e * p[4] + f * p[5] + g * p[6] + h * p[7] + i * p[8] + j * p[9])
x.sort()
for i in range(0, N):
	n = input()
	n = int(n)
	for i in range(0, len(x)):
		if x[i] == n:
			print(n)
			break
		if x[i] > n:
			print(x[i])
			break


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)


l = []
for i in range(19684):
	j = i
	f = 0
	while j > 0:
		x = j % 3
		j = j // 3
		if x == 2:
			f = 1
			break
	if not f:
		l.append(i)
for _ in range(int(input())):
	x = int(input())
	for j in l:
		if j >= x:
			print(j)
			break


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)


z = [1]
for k in range(1, 10):
	l = pow(3, k)
	z.append(l)
	n = len(z)
	for m in range(n - 1):
		a = z[m] + l
		z.append(a)
x = int(input())
for i in range(x):
	b = int(input())
	j = len(z)
	for i in range(j):
		if z[i] >= b:
			break
	print(z[i])


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)


import itertools

def binsearch(n, arr, val):
	if val <= arr[0]:
		return arr[0]
	i = 0
	j = n
	mid = 0
	while i < j:
		mid = (i + j) // 2
		if arr[mid] == val:
			return arr[mid]
		if val < arr[mid]:
			if mid > 0 and val > arr[mid - 1]:
				if val == arr[mid - 1]:
					return arr[mid - 1]
				return arr[mid]
			j = mid
		else:
			if mid < n - 1 and val < arr[mid + 1]:
				return arr[mid + 1]
			i = mid + 1
	return arr[mid]
pre = []
good = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683]
for L in range(len(good) + 1):
	for subset in itertools.combinations(good, L):
		st = sum(subset)
		if st <= 19683:
			pre.append(st)
pre.sort()
Q = int(input())
for q in range(Q):
	N = int(input())
	print(binsearch(len(pre), pre, N))


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
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 value():
	return tuple(map(int, input().split()))

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

def Int():
	return int(input())

def Str():
	return input()

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

def check(n):
	c = 0
	powers = set()
	while n > 0:
		while n % 3 == 0:
			c += 1
			n = n // 3
		n -= 1
		if c in powers:
			return False
		powers.add(c)
	return True
for _ in range(Int()):
	n = Int()
	while True:
		if check(n):
			print(n)
			break
		n += 1


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 math
for i in range(int(input())):
	s = t = int(input())
	l = []
	while s:
		l.append(math.floor(math.log(s, 3)))
		s -= math.pow(3, l[-1])
	n = 0
	while l:
		if len(l) == 1:
			n += math.pow(3, l.pop())
			break
		elif l[-1] == l[-2]:
			n = 0
			l.pop()
			l.append(l.pop() + 1)
			if len(l) > 1:
				if l[-1] > l[-2]:
					l.pop()
					l[-1] += 1
		else:
			n += math.pow(3, l.pop())
	print(int(n))


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)


hor = []
for a in range(2):
	for b in range(2):
		for c in range(2):
			for d in range(2):
				for e in range(2):
					for f in range(2):
						for g in range(2):
							for h in range(2):
								for i in range(2):
									for k in range(2):
										k = 3 ** 9 * a + 3 ** 8 * b + 3 ** 7 * c + 3 ** 6 * d + 3 ** 5 * e + 3 ** 4 * f + 3 ** 3 * g + 3 ** 2 * h + 3 ** 1 * i + 3 ** 0 * k
										if k > 0 and k < 20000:
											hor.append(k)
q = int(input())
for k in range(q):
	n = int(input())
	for i in range(len(hor)):
		if hor[i] >= n:
			print(hor[i])
			break


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


import math
li = []
for n in range(10000):
	l = []
	summ = 0
	while n > 0:
		no = int(math.log(n, 2))
		n = n - 2 ** no
		l += [no]
	for i in l:
		summ += 3 ** i
	li.append(summ)
for _ in range(int(input())):
	n = int(input())
	i = 0
	while li[i] < n:
		i = i + 1
	print(li[i])


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 base3(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		if r == 2:
			return 0
		nums.append(str(r))
	return ''.join(reversed(nums))
q = int(input())
aux = []
for k in range(19684):
	aux.append(base3(k))
	k += 1
for i in range(q):
	q = int(input())
	if q == 1:
		print(q)
	elif aux[q] != 0:
		print(q)
	else:
		while aux[q] == 0:
			q += 1
		print(q)


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()))))


from itertools import combinations
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
pwr = [3 ** i for i in x]
prefix = []
for _ in range(1, 10):
	x = list(combinations(pwr, _))
	for j in x:
		prefix += [sum(j)]
prefix = list(set(prefix))
prefix = sorted(prefix)
for i in range(int(input())):
	n = int(input())
	for el in prefix:
		if el >= n:
			print(el)
			break


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)


import os
import sys
from io import BytesIO, IOBase
from bisect import bisect

def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))
N = int(20000.0 + 3)
good = [x for x in range(1, N) if '2' not in ternary(x)]

def solution(n):
	idx = bisect(good, n)
	if good[idx - 1] == n:
		write(good[idx - 1])
	else:
		write(good[idx])

def main():
	for _ in range(r_int()):
		n = r_int()
		solution(n)
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))

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

def write(*args, end='\n'):
	for x in args:
		sys.stdout.write(str(x) + ' ')
	sys.stdout.write(end)

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

def r_int():
	return int(input())
main()


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)


import sys
input = sys.stdin.readline

def checkgood(n):
	while n > 0:
		if n % 3 == 2:
			return False
		n //= 3
	return True

def main():
	t = int(input())
	while t:
		t -= 1
		n = int(input())
		i = n
		while checkgood(i) == False:
			i += 1
		sys.stdout.write(str(i) + '\n')
main()


from itertools import combinations
from bisect import bisect_left
q = int(input())
p = [3 ** i for i in range(10)]
a = []
for i in range(10):
	s = list(combinations(p, i + 1))
	for j in range(len(s)):
		s[j] = sum(s[j])
	a.extend(s)
a = set(a)
a = list(a)
a.sort()
for _ in range(q):
	print(a[bisect_left(a, int(input()))])


amount = 10
three = [3 ** i for i in range(amount)]
q = int(input())
for _ in range(q):
	n = int(input())
	ans = list()
	for i in reversed(range(amount)):
		if n > three[i]:
			n -= three[i]
			ans.append(1)
		else:
			ans.append(0)
	if n != 0:
		for i in reversed(range(amount)):
			if ans[i] == 1:
				ans[i] = 0
			else:
				ans[i] = 1
				break
	result = 0
	for i in range(amount):
		result += ans[i] * three[amount - 1 - i]
	print(result)


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()


q = int(input())
mem = [1]
for i in range(1, 10):
	x = 3 ** i
	mem.append(x)
	for j in range(len(mem) - 1):
		mem.append(mem[j] + x)
for _ in range(q):
	n = int(input())
	low = 0
	high = len(mem) - 1
	while low <= high:
		mid = (low + high) // 2
		if mid == 0 or (mem[mid - 1] < n and mem[mid] >= n):
			break
		elif mem[mid - 1] >= n:
			high = mid - 1
		elif mem[mid + 1] <= n:
			low = mid + 1
	print(mem[mid])


pow3 = []
for i in range(10):
	pow3.append(3 ** i)
pow3
q = int(input())
for _ in range(q):
	n = int(input())
	i = 0
	while n > pow3[i]:
		i += 1
	ans = pow3[i]
	if n != pow3[i] and i > 0:
		sm = 0
		i -= 1
		sm += pow3[i]
		while sm < n and i > 0:
			i -= 1
			sm += pow3[i]
			if sm > n:
				ans = min(ans, sm)
				sm -= pow3[i]
		if sm == n:
			ans = sm
	print(ans)


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()


def check(n):
	i = 1
	while i <= n:
		i *= 3
	i //= 3
	while n > 0 and i != 0:
		if n >= i:
			n -= i
		i //= 3
	if n == 0:
		return True
	return False
q = int(input())
for _ in range(q):
	n = int(input())
	while True:
		if check(n):
			flag = 1
			break
		n += 1
	print(n)


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)


import math
q = int(input())
pw = [3 ** 0]
for i in range(1, 10):
	pw.append(3 ** i)
	length = len(pw)
	for j in range(length - 1):
		pw.append(3 ** i + pw[j])
for _ in range(q):
	n = int(input())
	for i in range(len(pw)):
		if n <= pw[i]:
			print(pw[i])
			break


def ternary(n):
	if n < 3:
		return [n]
	ret = ternary(int(n / 3))
	ret.append(n % 3)
	return ret

def good(n):
	push = 0
	if n % 3 == 2:
		n += 1
		push = 1
	if n == 0 or n == 1:
		return [n, 0]
	got = good(int(n / 3))
	lower = got[0]
	passed = got[1]
	ret = lower * 3
	if not passed:
		ret += n % 3
	else:
		push = passed
	return [ret, push]
a = int(input())
for _ in range(a):
	n = int(input())
	print(good(n)[0])


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)


import itertools

def good(num):
	lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
	gud = []
	for r in range(1, 11):
		for p in itertools.combinations(lst, r):
			s = 0
			for ele in p:
				s += 3 ** ele
			if s <= 3 ** 9:
				gud.append(s)
	gud.sort()
	for i in gud:
		if i >= num:
			return i
for test in range(int(input())):
	print(good(int(input())))


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)


import bisect
Q = int(input())
power = [1, 3]
for _ in range(8):
	power.append(power[-1] * 3)
status = [[] for _ in range(1 << 10)]
for mask in range(1 << 10):
	for i in range(10):
		status[mask].append(mask >> i & 1)
wa = []
for state in status:
	tmp = 0
	for i in range(len(state)):
		if state[i] == 1:
			tmp += power[i]
	wa.append(tmp)
wa.sort()
for _ in range(Q):
	N = int(input())
	index = bisect.bisect_left(wa, N)
	print(wa[index])


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))


i = 1
arr = []
while True:
	temp = i
	curr = 0
	a = 0
	while temp:
		bit = temp & 1
		if bit:
			a += 3 ** curr
		curr += 1
		temp = temp >> 1
	if i > 10 ** 4:
		break
	else:
		arr.append(a)
	i += 1
for _ in range(int(input())):
	n = int(input())
	for i in arr:
		if i >= n:
			print(i)
			break


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)


from sys import stdin
from bisect import bisect_right
input = stdin.readline

def generateCube():
	g = (pow(3, i) for i in range(0, 10))
	return list(g)

def find_le(l, x):
	i = bisect_right(l, x)
	if i:
		return i - 1

def isGood(n):
	idx = find_le(cube, n)
	while n > 0 and idx >= 0:
		if n - cube[idx] >= 0:
			n = n - cube[idx]
		idx -= 1
	if n == 0:
		return True
	else:
		return False
cube = generateCube()
for _ in range(int(input())):
	n = int(input())
	while not isGood(n) == True:
		n = n + 1
	print(n)


t = int(input())
for z in range(0, t):
	arr = []
	n = int(input())
	m = int(n)
	f = 0
	count = 0
	while m > 0:
		arr.append(m % 3)
		if m % 3 == 2:
			f = 1
		m = int(m / 3)
		count += 1
	ans = 0
	x = -1
	if f == 0:
		ans = n
	else:
		i = count - 1
		while arr[i] != 2:
			if arr[i] == 0:
				x = i
			i -= 1
		if x == -1:
			ans = pow(3, count)
		else:
			for k in range(0, x):
				arr[k] = 0
			arr[x] = 1
			for k in range(x, count):
				ans += pow(3, k) * arr[k]
	print(ans)
	print()


from itertools import combinations
arr = []
powers = []
for i in range(10):
	powers.append(3 ** i)
pre = []
for i in range(1, 10):
	x = list(combinations(powers, i))
	for j in x:
		pre.append(sum(j))
pre = list(set(pre))
pre.sort()
for i in range(int(input())):
	n = int(input())
	for j in pre:
		if j >= n:
			print(j)
			break


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


idx = []
for i in range(0, 2 ** 9):
	idx.append('{0:b}'.format(i).zfill(9))
mem = []
for i in idx:
	goodNumber = 0
	for l in range(0, len(i)):
		goodNumber += 3 ** l * int(i[l])
	mem.append(goodNumber)
mem.sort()
mem.append(19683)
q = int(input())
for i in range(0, q):
	n = int(input())
	p = 0
	while mem[p] < n:
		p += 1
	print(mem[p])


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


l = []

def f(i, s):
	global l
	if i == -1:
		l.append(s)
		return
	f(i - 1, s + 3 ** i)
	f(i - 1, s)
f(10, 0)
l.sort()
q = int(input())
for i in range(q):
	n = int(input())
	for e in l:
		if e >= n:
			print(e)
			break


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)


def chq3(n):
	po = 10
	s = set()
	while po >= 0:
		k = 3 ** po
		if n >= k:
			n -= k
		po -= 1
	return n == 0
for _ in range(int(input())):
	a = int(input())
	t = a
	while chq3(t) != 1:
		t += 1
	print(t)


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)