hello dawdler i am also beginner but was able to solve this question.
it is given that magic number can only contain 4 or 7 as digit only.
for example

4474 > 4477

4477 > 4744

777 > 4444
so you have only two case
when you have one of digit as 4 (example 1,2)
read from last digit and change 7 to 4 and 4 to 7 stop when
you change 4 to 7 for first time
when all digit consist of digit (example 3)
7 only
answer will be number consiting of all digit as 4 but of
length +1 than original
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
int t;
char a[150];
cin>>t;
while(t) { char a[150];
cin>>a;
int l=strlen(a),flag=0;
for(int i=0;i<l;i++)
{
if(a[i]=='4')
{
flag=1;
break;
}
}
if(flag==0)
{ for(int i=0;i<=l;i++)
cout<<'4';
cout<<endl;
}
if(flag==1)
{ int first=0;
for(int i=l1;i>=0&&first==0;i)
{
if(a[i]=='4'&&first==0)
{
a[i]='7';
first=1;
}
if(a[i]=='7'&&first==0)
{
a[i]='4';
}
}
for(int i=0;i<l;i++)
cout<<a[i];
cout<<endl;
}
}
return 0;
}