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; } }

26th Apr 2022, 9:56 AM
juanestragon 10
juanestragon 10 - avatar
4 odpowiedzi
+ 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".
26th Apr 2022, 10:06 AM
OrHy3
OrHy3 - avatar
+ 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; }
26th Apr 2022, 3:35 PM
Ipang
+ 1
Yes i noticed it, i changed after it returned always true
26th Apr 2022, 3:54 PM
juanestragon 10
juanestragon 10 - avatar
0
Thanks
26th Apr 2022, 10:07 AM
juanestragon 10
juanestragon 10 - avatar