Hi!I'm a sophomore IT student. We are asked to write function that would get as parameter a long integer number and determines whether the number is a palindrome. A number is a palindrome if it reads the same forward and backward. The function Palindrome should be called in the main program. This program somehow involves user define function.
ex: Input(x): 12321, then call PALINDROME(x)
Output : Palindrome : YES
Input(x): 12333, then call PALINDROME(x)
Output : Palindrome : NO
Can you give us some idea on how to solve this program?
Thank you!
if it would take a string then reversing the numbers for comparison would be easy. However, since it takes a long.. i'm not sure how to convert from int back into a string..
the only thing I can think of, is to use a bunch of modulo by 10's, or somethign similar to get the individual digits.
Let me experiment with it and see what I can come up with.
as soon as I hit submit, it came to mind. I have yet to try it yet, however.
but something along the line of
1 2 3 4 5 6 7 8 9 10 11
long original; // original number, i'll skip the step of putting a number into it, for this example.
vector<int> digits; // to hold the digits
while (original >= 10) // while more than 1 digit
{
int temp = original % 10; // get the last digit
digits.push_back(temp); // add it to vector
original = (original - temp) / 10; // get rid of last digit, and shift one
}
digits.push_back(original); // put last digit into vector
This is untested, but should seperate each digit into a vector, from which you can then do as you see fit, including reversing the order. I would make a copy, reversing the order in the process, then compare the two vectors.
Or, you can, after reversing the order, put it back together as thus:
1 2 3 4 5 6
long reversed; // to put the reversed number in
for (int i = 0; i < digits.size(); i++)
{
reversed *= 10; // shift everything to the left one
reversed += digits.at(i); // add new digit to end
}