c++ – I Want This Code To Prove If An Integer Is A Palindrome. How Do I do It?
I’m not sure what you’re trying to do in isPalindrome
.
One way to check if a string of size len
is palindrome is to compare its i
-th and (len-i-1)
-th characters for i
ranging in [0, len / 2)
.
If they differ at any point the string is not palindrome.
Here’s how you may do it:
bool isPalindrome(std::string const& md) {
if (md.empty()) // Empty strings are not palindrome
return false;
auto const len = md.size();
auto const halfLen = len / 2;
for (std::size_t i = 0; i != halfLen; ++i)
if (md[i] != md[len - i - 1])
return false;
return true;
}
Can anyone help me, and if possible, without changing much of the code tell
me ways to achieve what I want to (to prove palindrome-ism)?
Please check the comments I’ve added in the code:
// Include the correct headers
#include <iostream>
#include <string>
// Don't do this
//using namespace std;
// This just checks if the string is palindrome.
// It does not print anything.
bool isPalindrome(std::string const& md) {
if (md.empty())
return false;
auto const len = md.size();
auto const halfLen = len / 2;
for (std::size_t i = 0; i != halfLen; ++i)
if (md[i] != md[len - i - 1])
return false;
return true;
}
int main() {
// No need to parse the number and convert it to string again.
//int x;
std::string md;
std::cout << "What is the integer you wanna check palindromism for?: ";
// NOTE: you may input any string here: not just integers.
std::cin >> md;
std::cout << (isPalindrome(md) ? "YES" : "") << '\n';
// ^ print "YES" or nothing
return 0;
}
You may also implement isPalindrome
with algorithms and iterators like so:
// You'll need these two headers
#include <algorithm>
#include <iterator>
template <typename BidIt>
bool isPalindrome(BidIt first, BidIt last) {
if (first == last)
return false;
auto const halfLength = std::distance(first, last);
auto const mid = std::next(first, halfLength);
auto const rFirst = std::make_reverse_iterator(last);
return std::equal(first, mid, rFirst);
}
bool isPalindrome(std::string const& str) {
return isPalindrome(std::cbegin(str), std::cend(str));
}
This is basically the same algorithm as above but you can reuse
template <typename BidIt>
bool isPalindrome(BidIt, BidIt);
with more containers than just std::string
.
Read more here: Source link