0
Can somone help me with my polindrome solution in c++ please? I cannot figure out what is the issue here
#include <iostream> using namespace std; bool isPalindrome(int x) { int remainder; int reverse=0; while(x>0) { remainder=x/10; reverse=reverse*10 + remainder; x = x/10; } if(x!=reverse) {return false; } else{return true; } } int main() { int n; cin >>n; if(isPalindrome(n)) { cout <<n<<" is a palindrome"; } else { cout << n<<" is NOT a palindrome"; } return 0; }
2 Respuestas
+ 3
When calculating the remainder, you used division instead of modulo. However, the main issue is that you try to compare "reverse" and 'x' at the end, but 'x' will equal 0 at that point. You need to copy its value into a different variable to be able to compare it to the reversed number afterwards.
Here is a shortened approach for the isPalindrome() function:
int reverse{ 0 };
for ( int i{ x }; i != 0; i /= 10 )
{
reverse = reverse * 10 + i % 10;
}
return ( x == reverse );
0
Thank you:)