Alice is a very brilliant student. He considers '4' and '7' as Magic numbers. The numbers containing only magic numbers are also magical. Given a magic number N ,he wants to know what could be the next magical number greater than the given number.

-----Input-----

First line of input contains number of test cases T. For each test case, there is exits only one line containing a magic number N. 

-----Output-----

For each test case,  output a single line containing the next greater magical number.

-----Constraints-----
1<=T<=1000
4<= N<=10^100

-----Example-----
Input:
2
4
47

Output:
7
74

Source: codechef | Difficulty: UNKNOWN_DIFFICULTY


Solutions:
import math

def magic(a, digits):
	m = a % 10
	if m == 4:
		return a + 3
	elif m == 7:
		p = list(str(a))
		for i in range(digits - 1, -1, -1):
			if p[i] == '4':
				p[i] = '7'
				p = ''.join((str(n) for n in p))
				return int(p)
			if (p[i] == '7') & (i == 0):
				p[i] = '4'
				p.insert(0, 4)
				p = ''.join((str(n) for n in p))
				return int(p)
			if p[i] == '7':
				p[i] = '4'
t = eval(input())
n = []
op = []
for i in range(0, t):
	n.append(eval(input()))
for i in range(0, t):
	digits = int(math.log10(n[i])) + 1
	op.append(magic(n[i], digits))
for i in range(0, t):
	print(op[i])


k = int(input())
for char in range(k):
	num = int(input())
	if '4' not in str(num):
		x = len(str(num)) + 1
		print('4' * x)
	elif num % 2 == 0:
		print(num + 3)
	else:
		num = str(num)
		for i in range(len(num) - 1, -1, -1):
			if num[i] == '4':
				index = i
				break
		q = int(index)
		l = num[0:q]
		what = len(num) - (index + 1)
		print(l + '7' + '4' * what)


t = int(input())
for i in range(t):
	number = int(input())
	if '4' not in str(number):
		x = len(str(number)) + 1
		print('4' * x)
	elif number % 2 == 0:
		print(number + 3)
	else:
		number = str(number)
		for i in range(len(number) - 1, -1, -1):
			if number[i] == '4':
				index = i
				break
		q = int(index)
		u = number[0:q]
		lennew = len(number) - (index + 1)
		print(u + '7' + '4' * lennew)


def checkmagic(n):
	for i in range(0, len(n)):
		if n[i] != '4' and n[i] != '7':
			return False
	return True

def nextmag(n):
	n = str(n)
	n = list(n)
	n = n[::-1]
	n[0] = str(int(n[0]) + 1)
	s = []
	for i in range(0, len(n)):
		s.append('7')
	if int(''.join(n[::-1])) > int(''.join(s)):
		n.append('0')
	i = 0
	while checkmagic(n) == False and i < len(n):
		if int(n[i]) < 4:
			n[i] = '4'
		elif int(n[i]) < 7:
			n[i] = '7'
		else:
			n[i] = '4'
			n[i + 1] = str(int(n[i + 1]) + 1)
		i += 1
	return ''.join(n[::-1])
T = int(input())
a = []
for i in range(0, T):
	k = int(input())
	a.append(nextmag(k))
for e in a:
	print(e)


def process(N):
	if not '4' in N:
		return '4' * (len(N) + 1)
	i = N.rindex('4')
	return N[:i] + '7' + '4' * len(N[i + 1:])

def main():
	T = int(input().strip())
	for t in range(T):
		N = input().strip()
		print(process(N))
main()