import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Amine
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastInput in = new FastInput(inputStream);
        FastOutput out = new FastOutput(outputStream);
        AJuicer solver = new AJuicer();
        solver.solve(1, in, out);
        out.close();
    }

    static class AJuicer {
        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.nextInt();
            int b = in.nextInt();
            int d = in.nextInt();
            int sum = 0;
            for (int i = 0; i < n; i++) {
                int k = in.nextInt();
                if (k < b) sum += k;
            }
            out.println(sum / d);
        }

    }

    static class FastOutput {
        private final PrintWriter writer;

        public FastOutput(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public FastOutput(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void println(int i) {
            writer.println(i);
        }

    }

    static class FastInput {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastInput.SpaceCharFilter filter;

        public FastInput(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Amine
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastInput in = new FastInput(inputStream);
        FastOutput out = new FastOutput(outputStream);
        AJuicer solver = new AJuicer();
        solver.solve(1, in, out);
        out.close();
    }

    static class AJuicer {
        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.nextInt();
            int b = in.nextInt();
            int d = in.nextInt();
            int a[] = new int[n];
            int sum = 0;
            int res = 0;
            for (int i = 0; i < n; i++) {
                int k = in.nextInt();
                if (k < b) {
                    sum += k;
                    if (sum > d) {
                        res += sum / d;
                        sum = 0;
                    }
                }
            }
            out.println(res);
        /*long sum = 0;
        for (int i = 0; i < n; i++) {
            int k = in.nextInt();
            if (k < b) sum+=k;
        }
        out.println(sum/d);*/
        }

    }

    static class FastOutput {
        private final PrintWriter writer;

        public FastOutput(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public FastOutput(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void println(int i) {
            writer.println(i);
        }

    }

    static class FastInput {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastInput.SpaceCharFilter filter;

        public FastInput(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Amine
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastInput in = new FastInput(inputStream);
        FastOutput out = new FastOutput(outputStream);
        AJuicer solver = new AJuicer();
        solver.solve(1, in, out);
        out.close();
    }

    static class AJuicer {
        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.nextInt();
            int b = in.nextInt();
            int d = in.nextInt();
            int a[] = new int[n];
            int sum = 0;
            int res = 0;
            for (int i = 0; i < n; i++) {
                int k = in.nextInt();
                if (k <= b) {
                    sum += k;
                    if (sum > d) {
                        res += sum / d;
                        sum = 0;
                    }
                }
            }
            out.println(res);
        /*long sum = 0;
        for (int i = 0; i < n; i++) {
            int k = in.nextInt();
            if (k < b) sum+=k;
        }
        out.println(sum/d);*/
        }

    }

    static class FastOutput {
        private final PrintWriter writer;

        public FastOutput(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public FastOutput(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void println(int i) {
            writer.println(i);
        }

    }

    static class FastInput {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastInput.SpaceCharFilter filter;

        public FastInput(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Amine
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastInput in = new FastInput(inputStream);
        FastOutput out = new FastOutput(outputStream);
        AJuicer solver = new AJuicer();
        solver.solve(1, in, out);
        out.close();
    }

    static class AJuicer {
        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.nextInt();
            int b = in.nextInt();
            int d = in.nextInt();
            int a[] = new int[n];
            int sum = 0;
            int res = 0;
            for (int i = 0; i < n; i++) {
                int k = in.nextInt();
                if (k <= b) {
                    sum += k;
                    if (sum > d) {
                        res++;
//                    res+= sum/d;
                        sum = 0;
                    }
                }
            }
            out.println(res);
        /*long sum = 0;
        for (int i = 0; i < n; i++) {
            int k = in.nextInt();
            if (k < b) sum+=k;
        }
        out.println(sum/d);*/
        }

    }

    static class FastOutput {
        private final PrintWriter writer;

        public FastOutput(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public FastOutput(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void println(int i) {
            writer.println(i);
        }

    }

    static class FastInput {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastInput.SpaceCharFilter filter;

        public FastInput(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}


import java.util.Scanner;

public class submission {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int b = sc.nextInt();
		int d = sc.nextInt();
		int d1=d;
		int i=0,times=0;
		while(i<n){
			int input = sc.nextInt();
			if(input<b){
				d1-=input;
				if(d1<=0){times+=1;d1+=d;}
			}
			i++;
		}
		System.out.println(times);
	}

}


import java.util.Scanner;

public class submission {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int b = sc.nextInt();
		int d = sc.nextInt();
		int d1=d;
		int i=0,times=0;
		while(i<n){
			int input = sc.nextInt();
			if(input<b){
				d1-=input;
				if(d1<0){times+=1;d1+=d;}
			}
			i++;
		}
		System.out.println(times);
	}

}


import java.util.Scanner;

public class submission {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int b = sc.nextInt();
		int d = sc.nextInt();
		int sum=0;
		int i=0,times=0;
		while(i<n){
			int input = sc.nextInt();
			if(input>b) continue;
			sum+=input;
			if(sum>d){sum=0; times++;}
			i++;
		}
		System.out.println(times);
	}

}


import java.util.Scanner;

public class submission {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int b = sc.nextInt();
		int d = sc.nextInt();
		int d1=d;
		int i=0,times=0;
		while(i<n){
			int input = sc.nextInt();
			if(input<=b){
				d1-=input;
				if(d1<0){times+=1;d1+=d;}
			}
			i++;
		}
		System.out.println(times);
	}

}


import java.util.Scanner;

public class submission {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int b = sc.nextInt();
		int d = sc.nextInt();
		int sum=0;
		int i=0,times=0;
		while(i<n){
			int input = sc.nextInt();
			if(input<=b){
			sum+=input;
			if(sum>d){sum=0; times++;}
			}i++;
		}
		System.out.println(times);
	}

}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;

public class CF709A {
    public static void main(String[] args) {
        InputStream InputStream = System.in;
        OutputStream OutputStream = System.out;
        InputReader in = new InputReader(InputStream);
        PrintWriter out = new PrintWriter(OutputStream);

        int n = in.nextInt();
        int b = in.nextInt();
        int d = in.nextInt();

        long sum = 0;
        int emptyCount = 0;

        while(n-->0) {
            int orange = in.nextInt();

            if(orange<b)
                sum += orange;

            if(sum>d) {
                emptyCount++;
                sum = 0;
            }
        }

        out.print(emptyCount);

        out.close();
    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;

public class CF709A {
    public static void main(String[] args) {
        InputStream InputStream = System.in;
        OutputStream OutputStream = System.out;
        InputReader in = new InputReader(InputStream);
        PrintWriter out = new PrintWriter(OutputStream);

        int n = in.nextInt();
        int b = in.nextInt();
        int d = in.nextInt();

        long sum = 0;
        int emptyCount = 0;

        while(n-->0) {
            int orange = in.nextInt();

            if(orange<b)
                sum += orange;

            while(sum>d) {
                emptyCount++;
                sum -= d;
            }
        }

        out.print(emptyCount);

        out.close();
    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;

public class CF709A {
    public static void main(String[] args) {
        InputStream InputStream = System.in;
        OutputStream OutputStream = System.out;
        InputReader in = new InputReader(InputStream);
        PrintWriter out = new PrintWriter(OutputStream);

        int n = in.nextInt();
        int b = in.nextInt();
        int d = in.nextInt();

        int sum = 0;
        int emptyCount = 0;

        while(n-->0) {
            int orange = in.nextInt();

            if(orange<b)
                sum += orange;

            if(sum>d) {
                emptyCount++;
                sum -= d;
            }
        }

        out.print(emptyCount);

        out.close();
    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}


#------------------------------warmup----------------------------
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")

#-------------------game starts now-----------------------------------------------------
import math
def calc(n):
    k=n
    n1=int(math.log(n,3))
    if 2*n>(3**(n1+1)-1):
            return(3**(n1+1))
    while(n>=2):
        n1=int(math.log(n,3))
        n-=3**n1
        s.add(n1)
    if n==1 or n==0:
        return k
    else:
        t=0
        while(True):
            if t not in s:
                k=k+3**t-2
                return k
                break
            t+=1
for i in range(int(input())):
    n=int(input())
    s=set()
    print(calc(n))


#------------------------------warmup----------------------------
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")

#-------------------game starts now-----------------------------------------------------
import math
def calc(n):
    k=n
    n1=int(math.log(n,3))
    if 2*n>(3**(n1+1)-1):
            return(3**(n1+1))
    while(n>=2):
        n1=int(math.log(n,3))
        n-=3**n1
        s.add(n1)
    if n==1 or n==0:
        return k
    else:
        t=0
        while(True):
            if t not in s:
                k=k+3**t-2
                return k
                break
            t+=1
for i in range(int(input())):
    no=int(input())
    s=set()
    print(calc(no))


#------------------------------warmup----------------------------
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")

#-------------------game starts now-----------------------------------------------------
import math
def calc(n):
    k=n
    e=0
    n1=int(math.log(n,3))
    if 2*n>(3**(n1+1)-1):
            return(3**(n1+1))
    while(n>=2):
        n1=int(math.log(n,3))
        if 3**n1*3==n:
            n1+=1
        n-=3**n1
        print(3**n1)
        if n1 in s:
            e=n1
            break
        s.add(n1)
    if n==1 or n==0:
        return k
    else:
        t=e+1
        while(True):
            if t not in s:
                k=k+3**t-n-3**e*2
                return k
                break
            t+=1
for i in range(int(input())):
    n=int(input())
    s=set()
    print(calc(n))


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
        print('ma',ma)
        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)

if __name__ == '__main__':
    main()


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)

if __name__ == '__main__':
    main()


"""
    Satwik_Tiwari ;) .
    16 june , 2020  - Tuesday
"""

#===============================================================================================
#importing some useful libraries.
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  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================

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):
    """Prints the values to a stream, or to sys.stdout by default."""
    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)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
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")  #as stdout.write always print sring.
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) : # Check Prime Number or not
    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

#===============================================================================================
# code here ;))

def solve():
    n = int(inp())
    x = 40
    num = 0
    temp = n
    helpp = -1
    new = -1
    f = False
    while(temp > 0 and x >= 0):
        # print(temp,3**x)
        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)
    else:
        if(x >= 0):
            print(num+1)
        else:
            if(new == -1):
                print(3**(helpp+1))
            else:
                ans = num + 3**new
                x = 0
                while(x < new):
                    ans -= 3**x
                    x+=1
                print(ans)

# testcase(1)
testcase(int(inp()))


"""
    Satwik_Tiwari ;) .
    16 june , 2020  - Tuesday
"""

#===============================================================================================
#importing some useful libraries.
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  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================

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):
    """Prints the values to a stream, or to sys.stdout by default."""
    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)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
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")  #as stdout.write always print sring.
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) : # Check Prime Number or not
    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

#===============================================================================================
# code here ;))

def solve():
    n = int(inp())
    x = 40
    num = 0
    temp = n
    helpp = -1
    new = -1
    f = False
    while(temp > 0 and x >= 0):
        # print(temp,3**x)
        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)
    else:
        if(x >= 0):
            print(num+1)
        else:
            if(new == -1):
                print(3**(helpp+1))
            else:
                ans=  0
                while(ans < n):
                    ans += 3**new
                    new+=1
                print(ans)

# testcase(1)
testcase(int(inp()))


"""
    Satwik_Tiwari ;) .
    16 june , 2020  - Tuesday
"""

#===============================================================================================
#importing some useful libraries.
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  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================

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):
    """Prints the values to a stream, or to sys.stdout by default."""
    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)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
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")  #as stdout.write always print sring.
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) : # Check Prime Number or not
    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

#===============================================================================================
# code here ;))

def solve():
    n = int(inp())
    x = 40
    num = 0
    temp = n
    helpp = -1
    while(temp > 0 and x >= 0):
        if(temp < 3**x):
            x-=1
        else:
            if(helpp == -1):
                helpp = x
            num += 3**x
            temp -= 3**x
            x-=1

    if(temp == 0):
        print(num)
    else:
        if(x >= 0):
            print(num+1)
        else:
            print(3**(helpp+1))

# testcase(1)
testcase(int(inp()))


import os
import sys
from io import BytesIO, IOBase
# region fastio

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)

if __name__ == "__main__":
    main()


import os
import sys
from io import BytesIO, IOBase
# region fastio

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)

if __name__ == "__main__":
    main()


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)
    else:
        if 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)
            print(s)


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)
    else:
        if 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)


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)
    else:
        if pos0==-1:
            print("here")
            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)


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
##import numpy as np
##sys.setrecursionlimit(10**7)
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)
##    print(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

##        print(p2,pz)
        if(pz>p2):print(dp[n1])
        else:
            s=s[0:pz]+[1]+[0]*(n1-pz+1)
##            print(s)
            ans=0
            for i in range(n1-1,-1,-1):
                ans+=s[n1-i-1]*dp[i]
            print(ans)
    else:
        print(n)

##    if((n*(n+1)//2)%2):print("NO")
##    else:
##        print("YES")
##        print(n//2)
##        print(l[

##def msb(n):n|=n>>1;n|=n>>2;n|=n>>4;n|=n>>8;n|=n>>16;n|=n>>32;n|=n>>64;return n-(n>>1) #2 ki power
##def pref(a,n,f):
##    pre=[0]*n
##    if(f==0):         ##from beginning
##        pre[0]=a[0]
##        for i in range(1,n):
##            pre[i]=a[i]+pre[i-1]
##    else:              ##from end
##        pre[-1]=a[-1]
##        for i in range(n-2,-1,-1):
##            pre[i]=pre[i+1]+a[i]
##    return pre
##maxint=10**24
##def kadane(a,size):
##    max_so_far = -maxint - 1
##    max_ending_here = 0
##
##    for i in range(0, size):
##        max_ending_here = max_ending_here + a[i]
##        if (max_so_far < max_ending_here):
##            max_so_far = max_ending_here
##
##        if max_ending_here < 0:
##            max_ending_here = 0
##    return max_so_far
##def power(x, y):
##    if(y == 0):return 1
##    temp = power(x, int(y / 2))%mo
##    if (y % 2 == 0):return (temp * temp)%mo
##    else:
##        if(y > 0):return (x * temp * temp)%mo
##        else:return ((temp * temp)//x )%mo

##for _ in range(1):
##    n=inin()
##    l=ain()
##    d=dd(list)
##    dp=dd(set)
##    for k in range(n):
##        i=l[k]
##        dp[i].add(k)
##        b=bin(i)[2:]
##        c=0
##        for j in b[::-1]:
##            if j=='1':
##                d[c]+=[[i,k]]
##            c+=1
##    key=sorted(list(d.keys()),reverse=True)
##    ans=0
##    for i in key:
##        va=d[i]
##        va.sort(reverse=True)
##        p=len(va)
##        if(p!=0):
##            c=0;tans=0
##            for j,po in va:
##                if(po in dp[j]):
##                    c+=1
##                    f1,f2=j,po
##                    tans+=j
##                    dp[j].remove(po)
##            if(c%2==0 and c!=0):
##                c-=1
##
##            ans+=tans
##            print(ans,i,c,va)
##    print(ans)
##
##
##

##def msb(n):n|=n>>1;n|=n>>2;n|=n>>4;n|=n>>8;n|=n>>16;n|=n>>32;n|=n>>64;return n-(n>>1) #2 ki power
##def pref(a,n,f):
##    pre=[0]*n
##    if(f==0):         ##from beginning
##        pre[0]=a[0]
##        for i in range(1,n):
##            pre[i]=a[i]+pre[i-1]
##    else:              ##from end
##        pre[-1]=a[-1]
##        for i in range(n-2,-1,-1):
##            pre[i]=pre[i+1]+a[i]
##    return pre
##maxint=10**24
##def kadane(a,size):
##    max_so_far = -maxint - 1
##    max_ending_here = 0
##
##    for i in range(0, size):
##        max_ending_here = max_ending_here + a[i]
##        if (max_so_far < max_ending_here):
##            max_so_far = max_ending_here
##
##        if max_ending_here < 0:
##            max_ending_here = 0
##    return max_so_far
##def power(x, y):
##    if(y == 0):return 1
##    temp = power(x, int(y / 2))%mo
##    if (y % 2 == 0):return (temp * temp)%mo
##    else:
##        if(y > 0):return (x * temp * temp)%mo
##        else:return ((temp * temp)//x )%mo

##def msb(n):n|=n>>1;n|=n>>2;n|=n>>4;n|=n>>8;n|=n>>16;n|=n>>32;n|=n>>64;return n-(n>>1) #2 ki power
##def pref(a,n,f):
##    pre=[0]*n
##    if(f==0):         ##from beginning
##        pre[0]=a[0]
##        for i in range(1,n):
##            pre[i]=a[i]+pre[i-1]
##    else:              ##from end
##        pre[-1]=a[-1]
##        for i in range(n-2,-1,-1):
##            pre[i]=pre[i+1]+a[i]
##    return pre
##maxint=10**24
##def kadane(a,size):
##    max_so_far = -maxint - 1
##    max_ending_here = 0
##
##    for i in range(0, size):
##        max_ending_here = max_ending_here + a[i]
##        if (max_so_far < max_ending_here):
##            max_so_far = max_ending_here
##
##        if max_ending_here < 0:
##            max_ending_here = 0
##    return max_so_far
##def power(x, y):
##    if(y == 0):return 1
##    temp = power(x, int(y / 2))%mo
##    if (y % 2 == 0):return (temp * temp)%mo
##    else:
##        if(y > 0):return (x * temp * temp)%mo
##        else:return ((temp * temp)//x )%mo


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
##import numpy as np
##sys.setrecursionlimit(10**7)
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
        for i in range(n1-1,-1,-1):
            if(s[i]==2):
                s[i]=0
                c2+=1
            elif(s[i]==0):
                c2-=1
                if(c2>=0):s[i]=1
            if(c2<0):c2=0
        if(c2>0):print(dp[n1])
        else:
            ans=0
            for i in range(n1-1,-1,-1):
                ans+=s[n1-i-1]*dp[i]
            print(ans)
    else:
        print(n)

##    if((n*(n+1)//2)%2):print("NO")
##    else:
##        print("YES")
##        print(n//2)
##        print(l[

##def msb(n):n|=n>>1;n|=n>>2;n|=n>>4;n|=n>>8;n|=n>>16;n|=n>>32;n|=n>>64;return n-(n>>1) #2 ki power
##def pref(a,n,f):
##    pre=[0]*n
##    if(f==0):         ##from beginning
##        pre[0]=a[0]
##        for i in range(1,n):
##            pre[i]=a[i]+pre[i-1]
##    else:              ##from end
##        pre[-1]=a[-1]
##        for i in range(n-2,-1,-1):
##            pre[i]=pre[i+1]+a[i]
##    return pre
##maxint=10**24
##def kadane(a,size):
##    max_so_far = -maxint - 1
##    max_ending_here = 0
##
##    for i in range(0, size):
##        max_ending_here = max_ending_here + a[i]
##        if (max_so_far < max_ending_here):
##            max_so_far = max_ending_here
##
##        if max_ending_here < 0:
##            max_ending_here = 0
##    return max_so_far
##def power(x, y):
##    if(y == 0):return 1
##    temp = power(x, int(y / 2))%mo
##    if (y % 2 == 0):return (temp * temp)%mo
##    else:
##        if(y > 0):return (x * temp * temp)%mo
##        else:return ((temp * temp)//x )%mo

##for _ in range(1):
##    n=inin()
##    l=ain()
##    d=dd(list)
##    dp=dd(set)
##    for k in range(n):
##        i=l[k]
##        dp[i].add(k)
##        b=bin(i)[2:]
##        c=0
##        for j in b[::-1]:
##            if j=='1':
##                d[c]+=[[i,k]]
##            c+=1
##    key=sorted(list(d.keys()),reverse=True)
##    ans=0
##    for i in key:
##        va=d[i]
##        va.sort(reverse=True)
##        p=len(va)
##        if(p!=0):
##            c=0;tans=0
##            for j,po in va:
##                if(po in dp[j]):
##                    c+=1
##                    f1,f2=j,po
##                    tans+=j
##                    dp[j].remove(po)
##            if(c%2==0 and c!=0):
##                c-=1
##
##            ans+=tans
##            print(ans,i,c,va)
##    print(ans)
##
##
##

##def msb(n):n|=n>>1;n|=n>>2;n|=n>>4;n|=n>>8;n|=n>>16;n|=n>>32;n|=n>>64;return n-(n>>1) #2 ki power
##def pref(a,n,f):
##    pre=[0]*n
##    if(f==0):         ##from beginning
##        pre[0]=a[0]
##        for i in range(1,n):
##            pre[i]=a[i]+pre[i-1]
##    else:              ##from end
##        pre[-1]=a[-1]
##        for i in range(n-2,-1,-1):
##            pre[i]=pre[i+1]+a[i]
##    return pre
##maxint=10**24
##def kadane(a,size):
##    max_so_far = -maxint - 1
##    max_ending_here = 0
##
##    for i in range(0, size):
##        max_ending_here = max_ending_here + a[i]
##        if (max_so_far < max_ending_here):
##            max_so_far = max_ending_here
##
##        if max_ending_here < 0:
##            max_ending_here = 0
##    return max_so_far
##def power(x, y):
##    if(y == 0):return 1
##    temp = power(x, int(y / 2))%mo
##    if (y % 2 == 0):return (temp * temp)%mo
##    else:
##        if(y > 0):return (x * temp * temp)%mo
##        else:return ((temp * temp)//x )%mo

##def msb(n):n|=n>>1;n|=n>>2;n|=n>>4;n|=n>>8;n|=n>>16;n|=n>>32;n|=n>>64;return n-(n>>1) #2 ki power
##def pref(a,n,f):
##    pre=[0]*n
##    if(f==0):         ##from beginning
##        pre[0]=a[0]
##        for i in range(1,n):
##            pre[i]=a[i]+pre[i-1]
##    else:              ##from end
##        pre[-1]=a[-1]
##        for i in range(n-2,-1,-1):
##            pre[i]=pre[i+1]+a[i]
##    return pre
##maxint=10**24
##def kadane(a,size):
##    max_so_far = -maxint - 1
##    max_ending_here = 0
##
##    for i in range(0, size):
##        max_ending_here = max_ending_here + a[i]
##        if (max_so_far < max_ending_here):
##            max_so_far = max_ending_here
##
##        if max_ending_here < 0:
##            max_ending_here = 0
##    return max_so_far
##def power(x, y):
##    if(y == 0):return 1
##    temp = power(x, int(y / 2))%mo
##    if (y % 2 == 0):return (temp * temp)%mo
##    else:
##        if(y > 0):return (x * temp * temp)%mo
##        else:return ((temp * temp)//x )%mo


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)
        for j in range(i+1,co+1):
            ans+=li[-j]
        print(ans)


import math
import sys
input=sys.stdin.readline
for _ in range(int(input())):
    n=int(input())
    co=0
    li=[60]
    flag=True
    while(n):
        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)
        for j in range(i+1,co+1):
            ans+=li[-j]
        print(ans)


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)


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


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)


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
    # print(l)
    if pos == -1:
        print(orig)
    else:
        i = 0
        # print(l)
        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
            # print(l)
            for i in l:
                ans += i * pow(3, count)
                count += 1
            print(ans)
    t -= 1


# source for template https://github.com/cheran-senthil/PyRival/blob/master/templates/template_py3.py
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase

def main():
    pass

# region fastio

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
    print(l)
    if pos == -1:
        print(orig)
    else:
        i = 0
        # print(l)
        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
            print(l)
            for i in l:
                ans += i * pow(3, count)
                count += 1
            print(ans)
    t -= 1


'''input
8
1
2
6
13
14
3620
10000
1000000000000000000
'''
# A coding delight
from sys import stdin, stdout
from collections import defaultdict
import threading
import sys
from bisect import bisect_left, bisect_right
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[index] + second[index  - 1]
		else:
			return second[index]

# main starts
first = get_subset(0, 18)
second =get_subset(19, 38)

check = [1, 3, 4, 9, 10, 12, 13, 27, 28, 30]
q = int(stdin.readline().strip())
for _ in range(q):
	n = int(stdin.readline().strip())
	print(query(n))


'''input
8
1
2
6
13
14
3620
10000
1000000000000000000
'''
# A coding delight

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)):
		temp = 0
		for j in range(l):
			if (1 << j) & k:
				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[index] + second[index  - 1]
		else:
			return second[index]

# main starts
# import time
# i = time.time()
first = get_subset(0, 18)
second =get_subset(19, 38)
# print(time.time() - i)
q = int(stdin.readline().strip())
for _ in range(q):
	n = int(stdin.readline().strip())
	print(query(n))


'''input
8
1
2
6
13
14
3620
10000
1000000000000000000
'''
# A coding delight

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)):
		temp = 0
		for j in range(l):
			if (1 << j) & k:
				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]

# main starts
# import time
# i = time.time()
first = get_subset(0, 18)
second =get_subset(19, 38)
# print(time.time() - i)
q = int(stdin.readline().strip())
for _ in range(q):
	n = int(stdin.readline().strip())
	print(query(n))


'''input
8
1
2
6
13
14
3620
10000
1000000000000000000
'''
# A coding delight

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[index] + second[index  - 1]
		else:
			return second[index]

# main starts
# import time
# i = time.time()
first = get_subset(0, 18)
second =get_subset(19, 38)
# print(time.time() - i)
q = int(stdin.readline().strip())
for _ in range(q):
	n = int(stdin.readline().strip())
	print(query(n))


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]:
                # print(n,i,i+1,z[i],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)
        # print("__________")

    #<--Solving Area Ends
    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

if __name__ == '__main__':
    sys.stdin = FastStdin()
    sys.stdout = FastStdout()
    main()


import sys
#from collections import deque
#from functools import *
#from fractions import Fraction as f
from copy import *
from bisect import *
#from heapq import *
#from math import ceil
#from itertools import permutations ,product

def eprint(*args):
    print(*args, file=sys.stderr)
zz=1

#sys.setrecursionlimit(10**6)
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)


t=int(input())
def ternary(n):
    e = n//3
    q = n%3
    if n == 0:
        return '0'
    elif e == 0:
        return str(q)
    else:
        return ternary(e) + str(q)

from math import *
while t>0:
    t-=1
    n=int(input())
    a=ternary(n)
    a=str(a)
    a=list(a)
    p=int(ceil(log(n,3)))
    #print(a)
    a.reverse()
    flag=0
    c=0
    #print(a)
    for i in range(len(a)):
        if a[i]=='2':
            if a[i+1:].count('0')==0:
                flag=12
                break
            else:
                a[i]='0'
                #print(a[i+1:].index('0'))
                a[a[i+1:].index('0')+i+1]='1'
                #print(a)
    #print(a[::-1])
    if flag:
        print(3**p)
    else:
        print(int("".join(a[::-1]),3))


import sys
#from collections import deque
#from functools import *
#from fractions import Fraction as f
from copy import *
from bisect import *
#from heapq import *
#from math import ceil
#from itertools import permutations ,product

def eprint(*args):
    print(*args, file=sys.stderr)
zz=1

#sys.setrecursionlimit(10**6)
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)
	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=s[:i]+(len(s)-i)*"0"
			break
		elif s[i]=='0':
			flag=min(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)


import sys
#from collections import deque
#from functools import *
#from fractions import Fraction as f
from copy import *
from bisect import *
#from heapq import *
#from math import ceil
#from itertools import permutations ,product

def eprint(*args):
    print(*args, file=sys.stderr)
zz=1

#sys.setrecursionlimit(10**6)
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[:i])+(len(s)-i)*"0"
			break
		elif s[i]=='0':
			flag=min(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)


t=int(input())
def ternary(n):
    e = n//3
    q = n%3
    if n == 0:
        return '0'
    elif e == 0:
        return str(q)
    else:
        return ternary(e) + str(q)

from math import *
while t>0:
    t-=1
    n=int(input())
    a=ternary(n)
    a=str(a)
    a=list(a)
    p=int(ceil(log(n,3)))
    #print(a)
    flag=0
    c=0
    for i in range(len(a)):

        if a[0]=='2':
            flag=1
            break
        if a[i]!='0' and c==1:
            a[i]='0'
        elif a[i]=='2'  and a[i-1]=='0':
            a[i-1]='1'
            a[i]='0'
            c=1
        elif a[i]=='2' and a[i-1]!='0':
            flag=1
            break
    d=0
    #print(a)
    if flag and a[0]!='2':
        for i in range(1,len(a)):
            if a[i]=='2' and a[i-1]!='0':
                d=0
                break
            if d==1:
                a[i]='0'
            elif a[i]=='1'  and a[i-1]=='0':
                a[i-1]='1'
                a[i]='0'
                d=1

    #print(a)
    if d:
        print(int("".join(a),3))
    elif flag:
        print(3**p)
    else:
        print(int("".join(a),3))


import sys
#from collections import deque
#from functools import *
#from fractions import Fraction as f
from copy import *
from bisect import *
#from heapq import *
#from math import ceil
#from itertools import permutations ,product

def eprint(*args):
    print(*args, file=sys.stderr)
zz=1

#sys.setrecursionlimit(10**6)
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
	print("".join(s))
	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)


import sys
#from collections import deque
#from functools import *
#from fractions import Fraction as f
from copy import *
from bisect import *
#from heapq import *
#from math import ceil
#from itertools import permutations ,product

def eprint(*args):
    print(*args, file=sys.stderr)
zz=1

#sys.setrecursionlimit(10**6)
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[:i])+(len(s)-i)*"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)


t = int(input())

def conv(n):
    ans = []
    for i in range(40, -1, -1):
        if (3**i)*2 <= n:
            n -= 2*(3**i)
            ans.append(2)
        elif 3**i <= n:
            n -= 3**i
            ans.append(1)
        else:
            ans.append(0)

    return ans

for _ in range(t):
    n = int(input())
    c = conv(n)
    if 2 not in c:
        print(n)
    else:
        ind = c.index(2)
        c[ind] = 0
        for i in range(ind+1, len(c)):
            c[i] = 0

        for i in range(ind-1, -1, -1):
            if c[i] == 0:
                c[i] = 1
                break

        ans = 0
        for i in range(len(c)):
            ans += c[i]*3**(len(c)-i-1)

        print(ans)


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)


t = int(input())

def conv(n):
    ans = []
    for i in range(40, -1, -1):
        if (3**i)*2 <= n:
            n -= 2*(3**i)
            ans.append(2)
        elif 3**i <= n:
            n -= 3**i
            ans.append(1)
        else:
            ans.append(0)

    return ans

for _ in range(t):
    n = int(input())
    c = conv(n)
    if 2 not in c:
        print(n)
    else:
        c = c[::-1]
        for i in range(len(c)-1):
            if c[i] == 2 or c[i] == 3:
                c[i+1] += 1
                c[i] = 0

        c = c[::-1]
        ans = 0

        for i in range(len(c)):
            if c[i] == 1:
                ans += c[i]*(3**(len(c)-i-1))
                break

        print(ans)


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

    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
        # print(t, decimal(t))

    if t[0] > 1:
        print(3 ** maxpower(n))
    else:
        print(decimal(t))


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:
                t[i] = 1
                t[i - 1] += 1
            i -= 1
            # print(t, decimal(t))

        if t[0] > 1:
            print(3 ** maxpower(n))
        else:
            print(decimal(t))


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[i] = 0
                t[i - 1] += 1
            i -= 1
            # print(t, decimal(t))

        if t[0] > 1:
            print(3 ** maxpower(n))
        else:
            print(decimal(t))


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:
        if not isgood(n):
            print(3 ** maxpower(n))
        else:
            print(n)


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**9:
        while not isgood(n):
            n += 1
    else:
        if not isgood(n):
            print(3 ** maxpower(n))
        else:
            print(n)


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
            # print(t, decimal(t))

        if t[0] > 1:
            print(3 ** maxpower(n))
        else:
            print(decimal(t))


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:
                t[i] = 1
                t[i - 1] = t[i - 1] + 1
            i -= 1
            # print(t)

        # print(t)

        if t[0] == 2:
            print(3 ** maxpower(n))
        else:
            print(decimal(t))


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**9:
        while not isgood(n):
            n += 1
        print(n)
    else:
        if not isgood(n):
            print(3 ** maxpower(n))
        else:
            print(n)


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 < 0: #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:
                t[i] = 1
                t[i - 1] = t[i - 1] + 1
            i -= 1
            # print(t)

        # print(t)

        if t[0] == 2:
            print(3 ** maxpower(n))
        else:
            print(decimal(t))


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 not isgood(n):
        print(3 ** maxpower(n))
    else:
        print(n)


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**12:
        while not isgood(n):
            n += 1
        print(n)
    else:
        if not isgood(n):
            print(3 ** maxpower(n))
        else:
            print(n)


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**16:
        while not isgood(n):
            n += 1
        print(n)
    else:
        if not isgood(n):
            print(3 ** maxpower(n))
        else:
            print(n)