#include #include #include #include #include #include #include #include #include #include #define ll long long #define ull unsigned long long #define lson l, m, rt<<1 #define rson m+1, r, rt<<1|1 using namespace std; const int inf = 0x3f3f3f3f; const int M = 75; const int mod = 7; int a[25], ans[25]; bool dfs(int i, int cnt){ if(i == 0){ int fff = 0; if(ans[i] == -1){ if(a[i] > 7) return 0; else if(a[i] >4) ans[i] = 7; else{ ans[i] = 4; fff = 1; } } int num = 0; for(int j = 0; j < cnt; j++){ if(ans[j] == 4) num++; } if(fff && num == (cnt/2+1)){ ans[i] = 7; num--; } if(num*2 == cnt) return 1; else{ ans[i] = -1; return 0; } } if(a[i] < 4){ int num = 0; for(int j = cnt-1; j > i; j--){ if(a[j] == 4) num++; } for(int j = i; j >= 0; j--){ if(num < cnt/2){ ans[j] = 4; num++; } else ans[j] = 7; } if(dfs(0, cnt)) return 1; else return 0; } if(a[i] > 7){ ans[i] = -1; return 0; } if(a[i] == 7){ ans[i] = 7; if(dfs(i-1, cnt)) return 1; else return 0; } if(a[i] == 5 || a[i] == 6){ ans[i] = 7; int num = 0; for(int j = cnt-1; j >= i; j--){ if(ans[j] == 4) num++; } for(int j = i-1; j >= 0; j--){ if(num < cnt/2){ ans[j] = 4; num++; } else ans[j] = 7; } if(dfs(0, cnt)) return 1; else return 0; } ans[i] = 4; if(dfs(i-1, cnt)) return 1; else{ ans[i] = 7; int num = 0; for(int j = cnt-1; j >= i; j--){ if(ans[j] == 4) num++; } for(int j = i-1; j >= 0; j--){ if(num < cnt/2){ ans[j] = 4; num++; } else ans[j] = 7; } if(dfs(0, cnt)) return 1; else return 0; } } int main() { //freopen("input.txt", "r", stdin); int t; cin>>t; while(t--){ ll n; scanf("%lld", &n); int cnt = 0; while(n){ a[cnt++] = n%10; n /= 10; } int f = 0; if(cnt%2 == 0 && a[cnt-1] > 7){ cnt += 2; f = 1; } if(cnt%2 || f){ for(int i = 1; i <= (cnt+1)/2; i++) cout<<"4"; for(int i = 1; i <= (cnt+1)/2; i++) cout<<"7"; cout<= 0; u--){ cout<