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

# Thread: How to solve the Palindrome Problem in C++

1. Junior Member
Join Date
Oct 2022
Posts
7

## How to solve the Palindrome Problem in C++

I'm having trouble writing a C++ program to determine whether a number is a palindrome. My code is returning false even when the number is a palindrome. For instance, 12321 is a palindrome number, but 1451 is not.

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;
}
}```
Can anyone confirm if the code referenced from this is correct?
Last edited by Coreycoder; March 2nd, 2023 at 12:49 AM.

2. ## Re: How to solve the Palindrome Problem in C++

Consider as C++20:

Code:
```#include <iostream>
#include <iterator>
#include <format>
#include <concepts>

using fmt_to = std::ostream_iterator<char>;
const auto fmt_cout { fmt_to(std::cout) };

bool checkPalindrome(std::unsigned_integral auto original) {
unsigned reverseNum {};

for (auto tempOriginal { original }; tempOriginal > 0; tempOriginal /= 10)
reverseNum = reverseNum * 10 + tempOriginal % 10;

return original == reverseNum;
}

int main() {
constexpr const auto fmt { "{:>5}  {}\n" };

for (const unsigned i : {12321, 1451, 1, 23, 22})
std::format_to(fmt_cout, fmt, i, checkPalindrome(i));
}```
which displays:

Code:
```12321  true
1451  false
1  true
23  false
22  true```
Last edited by 2kaud; March 1st, 2023 at 11:40 AM.

3. ## Re: How to solve the Palindrome Problem in C++

Another approach is to convert the number to a std::string and then check that this is a palindrome. Consider:

Code:
```bool checkPalindrome(std::unsigned_integral auto original) {
const auto str { std::to_string(original) };

return str == std::string { str.rbegin(), str.rend() };
}```
or using std::ranges:

Code:
```bool checkPalindrome(std::unsigned_integral auto original) {
const auto str { std::to_string(original) };

return str == std::ranges::to<std::string>(str | std::views::reverse);
}```
Last edited by 2kaud; March 1st, 2023 at 11:37 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
•