-
seperating numbers
I am to determine if a number is a palindrome.
How do i go about seperating a 7 digit number to see if it is a palindrome.
I can only use basic if/else statements and other basic knowledge.
How do i seperate a 7 digit number into single digits to compare?
-
1) find out the number of digits your number has.
2) seperate your number into all the digits
3) check each number with its opposite
4) if every number matches a pattern, say so
this is fairly easy to implement.
-
Have a search around for how to use modulus. It will show you how to split the number up.
-
Its easier to turn the number into a char array....
Code:
#include <iostream>
#include <cstdio>
using std::cout;
using std::endl;
bool isPal(int y){
int a,b,c;
char buff[20];
b = sprintf(buff,"%d",y);//get char array
c = b / 2;//times to loop. If odd, then carry is lost
for(a = 0,--b;c;a++,b--,c--){
if(buff[a] == buff[b])
continue;//Same.....good, go again
else{//1 difference, so no pallindrome
cout << buff << " is not a palindrome" << endl;
return false;
}
}
cout << buff << " is a palindrome" << endl;
return true;
}
int main()
{
isPal(2552);//Yes
isPal(2556);//No
isPal(78987);//Yes
isPal(56874);//No
return 0;
}