Palindrome Problem in C++
hello Everyone, I'm trying to write a C++ program to find if palindrome number. Here's my code. The problem is that the program returns false even when the number is a palindrome. For example, the number 12321 is a palindrome number, but 1451 is not a palindrome number.
Code:
bool checkPalindrome(int original) {
int reverseNum = 0;
int tempOriginal = original;
while (tempOriginal > 0) {
int lastDigit = tempOriginal % 10;
reverseNum = reverseNum * 10 + lastDigit;
tempOriginal = tempOriginal / 10;
}
if (original == reverseNum) {
return true;
} else {
return false;
}
}
I have taken this code reference from this post. Can anyone tell me, Is this logic right?
Re: Palindrome Problem in C++
It's now a very good reason to learn how to debug yor code, debug it and found out what goes wrong and why.
Re: Palindrome Problem in C++
Code:
#include <iostream>
#include <iomanip>
bool checkPalindrome(unsigned original) {
unsigned reverseNum {};
for (auto tempOriginal {original}; tempOriginal > 0; tempOriginal /= 10)
reverseNum = reverseNum * 10 + tempOriginal % 10;
return original == reverseNum;
}
int main() {
std::cout << "1234 " << std::boolalpha << checkPalindrome(1234) << '\n';
std::cout << "1331 " << std::boolalpha << checkPalindrome(1331) << '\n';
std::cout << "12321 " << std::boolalpha << checkPalindrome(12321) << '\n';
std::cout << "1451 " << std::boolalpha << checkPalindrome(1451) << '\n';
}
Code:
1234 false
1331 true
12321 true
1451 false
Re: Palindrome Problem in C++
Quote:
Originally Posted by
aartiyadav
The problem is that the program returns false even when the number is a palindrome.
Are you sure? I could not spot a bug, so I ran your code with jverd's test set in #3 and the results are identical. It suggests your code is working. Still, it will not work with negative integers. If you want that you need to make this change to the while loop,
Code:
while (tempOriginal != 0) {
And it will only work with integers up to 9-10 digits. That is the limit for a 32-bit integer. You can double this by using a 64-bit integer (a long long int).