CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

# Thread: Palindrome Problem in C++

1. Junior Member
Join Date
Mar 2022
Posts
3

## 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?

2. ## 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.

3. ## 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```
Last edited by 2kaud; May 19th, 2022 at 03:37 AM.

4. Member +
Join Date
Feb 2017
Posts
653

## Re: Palindrome Problem in C++

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).
Last edited by wolle; May 22nd, 2022 at 12:45 AM.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•