When I compile my code for this question SPALNUM I am getting time limit exceeded! why?

enter code here

#include <iostream>

using namespace std;

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int l, r, sum = 0;
        cin>>l>>r;
        for(int i = l; i <= r; i++)
        {
            int rem;
            int temp = 0;
            int tempnum = i;

            while(i != 0)
            {
                rem = i % 10;
                i = i / 10;
                temp = temp*10 + rem;
            }
            if (tempnum == temp)
                sum += temp;
        }
        cout<<sum<<endl;
        sum = 0;
    }
    return 0;
}

Please post your code in more clear way

Here is the python Solution …

Precompute the palindromes till 10^5+1 and then just query… by applying BinarySearch . You will not get TLE

from bisect import bisect_left

l=([i for i in range(1,10)])

m=10**5+1

for i in range(10,m):

x=str(i)

if x[::-1]==x:

    l.append(i)

t=input()

while t>0:

t-=1

l1,r=map(int,raw_input().split())

x=bisect_left(l,l1)

y=bisect_left(l,r)

ct=0

for i in xrange(x,y+1):

    if i<len(l) and l[i]<=r and l[i]>=l1:

        ct+=l[i]


print ct

@neerajjha_1994 Here is your modified code which gets AC.

The problem in your code is that you use the same variable i for the for loop as well as the while loop .
After the while loop terminates i for sure is 0 and the for loop condition keeps on satisfying (i<=r) , hence this turns into an infinite loop(reason you get TLE) .

Just store i in another variable and use that variable for your while loop .

Hope this helps :smiley:

2 Likes

well thanks but one fine day I saw that I have the same name for inner and outer loop variables corrected it and it was accepted

If your problem is solved , accept the correct answer so that no more people answer here.