Search code examples
calgorithmfor-loopwhile-looppalindrome

C: time limit for FOR loop vs WHILE loop


I was solving the palindrome problem on leetcode using c, the algorithm with for loop gave me error saying "time limit exceeded" while it works fine for the while loop.

For Loop algorithm :

int temp, reverse = 0;
for(temp = x; temp > 0; temp/10){                // x is the variable to be tested
   reverse = reverse*10 + temp%10;
} 
if(reverse == temp){
   return true;
}
return false;

While loop algorithm:

int temp, reverse = 0; 
temp = x;                  // x is the variable to be tested
while(temp>0){
   reverse = reverse*10 + temp%10;
   temp = temp/10;
}
if(reverse == temp){
   return true;
}
return false;

I am not able to understand why is that the case? can anyone explain it to me.


Solution

  • The expression temp/10 calculates the division, but then throws away the result. The variable temp will not be modified, leading to an infinite loop.

    Use e.g. temp /= 10, which is equivalent to temp = temp / 10, to assign the result back to temp.


    That you use temp = temp / 10 in your while loop should have been a pretty big hint.