jharna agrawal
jharna agrawal

Reputation: 1

How to resolve time out error in my java code

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

Answers (1)

Stephen C
Stephen C

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.

  • The outer loop increases the loop variable a by 1 from i to j
  • The inner loop decreases the same loop variable 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

Related Questions