0
Why this always return true?
#include <iostream> using namespace std; bool isPalindrome(int x) { int z=x; int inv=0; while(x>0){ inv=inv*10; inv= inv+x%10; x=x/10; } if(x=inv){ return true; } else{ return false; } }
4 Respuestas
+ 4
"x = inv" means you're assigning to x the value of inv, it is not a comparison. The return value of this kind of expression is always the value you're assigning, meaning the only case it can return false is when x = 0, so that "x = inv" results in 0. To make this work simply substitute "x = inv" with "x == inv".
+ 1
Just an additional note to notice
I saw you copied <x> to <z> and I thought you did it to preserve <x> value cause <x> will be compared against <inv> to decide the function's return value.
The while...loop should use <z> instead of <x>.. We don't want <x> value to change.
while( z )
{
inv = inv * 10 + z % 10;
z /= 10;
}
+ 1
Yes i noticed it, i changed after it returned always true
0
Thanks