This function seems to be working for numbers with an odd number of digits but not for every number with an even number of digits (e.g. it returns true for 2662 but not for 906609). I've been trying to figure it out for the last 20-30 minutes but I haven't found out why.
#include <math.h>
int digits(int n)
{
return log10(n)+1;
}
bool ispalindrome(int n)
{
int c=digits(n);
for(int i=0; i<c/2; i++){
int a=pow(10,i),b=pow(10,c-i-1);
if( int(n/a) %10 != int(n/b) %10 ) return false;
}
return true;
}
#include <iostream>
#include <cstdlib>
int main(int, char**argv)
{
while (*++argv)
std::cout << *argv
<< (ispalindrome(std::atoi(*argv)) ? " is a palindrome." : " is not a palindrome.")
<< std::endl;
}
I can't reproduce, but I think it'll be easier to compare int as a string == reversedString:
bool isPalindrome(const int& n)
{
std::stringstream ssN;
ssN << n;
auto numberAsString = ssN.str();
auto reversed = numberAsString;
std::reverse(numberAsString.begin(), numberAsString.end());
return numberAsString == reversed;
}
Please, check the code: main.cpp