Reputation: 1
How to resolve timeout error in my java code:
This code first finds reverse of the element and then find out the difference between the actual and reverse value if that difference is divisible by k then increase the counter
Please find below code :
//all header files are included
public class Solution {
// Complete the beautifulDays function below.
static int beautifulDays(int i, int j, int k) {
int count=0;
for(int a=i;a<=j;a++)
{
int p=a;
int t=0,r=0;
while(a>0)
{
r=a%10;
t=t*10+r;
a=a/10;
}
if((t-p)%k==0)
count++;
}
return count;
}
// all other code of input and calling methods
Upvotes: 0
Views: 221
Reputation: 718906
You have an infinite loop in this section:
for (int a = i; a <= j; a++) {
int p = a;
int t = 0, r = 0;
while (a > 0) {
r = a % 10;
t = t * 10 + r;
a = a / 10; //OUCH!
}
}
Lets analyze this.
a
by 1
from i
to j
a
until it reaches zero.Guess which one wins? (Can't guess? Try a pencil and paper and "hand execute" these loops. It is a useful exercise.)
That means .... that the outer loop will never terminate.
Solution: use a different loop variable in the inner loop.
Upvotes: 1