How do I check for a palindrome and check the n amount of numbers to make it one?
Feb 19, 2016 at 10:23pm UTC
Write your question here.
I'm trying to make a program that takes user input of an integer and outputs whether or not it is a palindrome. If it is not a palindrome the program will make it into one using the shortest number of digits. Then it has to output how many digits were needed to make it into a palindrome. I think I'm close, but my code just won't work. What do I need to fix? And I still have no idea how to count the number of integers to make it a palindrome.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cmath>
using namespace std;
const int maxDigits(5);
int getInt(void );
bool isPal(int );
int makePal(int );
int rev(int );
unsigned numDigits(int );
int main(int argc, char *argv[]) {
bool pal;
int n;
cout << "Enter integers, with number of digits not greater than " << maxDigits << endl;
while (1) {
while (numDigits(n = getInt()) > maxDigits);
cout << (((pal = isPal(n)) == true ) ? "" : "not " ) << "a palindrome" ;
if (pal == false ) {
n = makePal(n);
cout << endl << n << " is " << ((isPal(n) == true ) ? "" : "not " ) << "a palindrome" ;
}
cout << endl << endl;
}
return 0;
}
bool isPal(int n) {
return abs(n) == rev(abs(n));
}
int makePal(int n) {
int z = pow(10, numDigits(abs(n)) - 1), revN = rev(abs(n));
return abs(n) * z + (revN % z);
}
int rev(int n) {
int m,y;
if (n < 10) return n;
for (m = n % 10,y = n; y >= 10; y /= 10) m *= 10;
return m + rev(n/10);
}
unsigned numDigits(int n) {
if (abs(n) < 10) return 1;
return 1 + numDigits(abs(n) / 10);
}
int getInt() {
stringstream ss;
string line;
bool inputOk = false ;
int n;
cout << "> " ;
do {
getline(cin,line);
ss.clear(); ss.str(line);
if ((!(ss >> n)) || (ss.good())) {
cout << endl << "invalid input, try again" << endl << "> " ;
} else {
inputOk = true ;
}
} while (inputOk == false );
return n;
}
#if 0
Topic archived. No new replies allowed.