I have been in this situation many times where often its difficult to estimate the number of iterations and hence the close bound on worst case time complexity. Here is the problem :
You are given a number N. You keep adding the number N with its reverse, until you obtain the palindrome. e.g. 327 is given.
327 + 723 = 1050
1050 + 0501 = 1551
You stop
You can have following assumptions :
- Solutions always exists
- The max value of resulting palindrome will never cross 2^32 (4-bit int enough)
Here is my code :
unsigned long rev(unsigned long k) //log k
{
unsigned long res = 0;
while(k)
{
res = res * 10 + k%10;
k = k/10;
}
return res;
}
int main()
{
int t,iter;
unsigned long n,res;
cin >> t;
while(t--)
{
cin >> n;
iter = 0;
while(1) //how many times this loop runs?
{
iter++;
res = n + rev(n);
if(res == rev(res)) //is a palindrome
break;
else
n = res;
}
cout << iter << " " << res << endl;
}
return 0;
}
What would be the time complexity in this case?
This depends on how many times the inner while loop runs in worst case. The worst case happens when the number starts from 10 and jumps to the largest palindrome before 2^32. But how many jumps will it take is again difficult to estimate.
Perhaps in this case we can apply certain mathematics to estimate the iterations, but what if the situation is randomized by doing random algebra (+,-,*) before a palindrome is reached. How do we quote time complexity in those random situations?
Aucun commentaire:
Enregistrer un commentaire