A “Palindrome Number” is a number that remains the same when its digits are reversed.
For example, 121 and 454 are palindrome numbers, but 123 and 789 are not. The problem is to determine whether a given integer is a palindrome or not?
To solve this problem in C++, we can follow the steps below:
- Convert the integer to a string.
- Compare the characters from both ends of the string, moving towards the middle, to check if they are the same.
Here’s an optimized C++ solution for the “Palindrome Number” problem:
#include <iostream>
using namespace std;
bool isPalindrome(int x) {
if (x < 0) {
return false; // Negative numbers are not palindromes
}
string numStr = to_string(x);
int left = 0;
int right = numStr.length() - 1;
while (left < right) {
if (numStr[left] != numStr[right]) {
return false;
}
left++;
right--;
}
return true;
}
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
if (isPalindrome(num)) {
cout << num << " is a palindrome." << endl;
} else {
cout << num << " is not a palindrome." << endl;
}
return 0;
}
This solution first handles negative numbers by returning false
since negative numbers cannot be palindromes. Then, it converts the given integer to a string and uses two pointers (left
and right
) to compare characters from both ends of the string. If the characters at left
and right
indices are not the same, it returns false
. Otherwise, it continues moving towards the middle of the string. If the loop completes without finding any mismatch, it means the number is a palindrome, and the function returns true
.
This approach has a time complexity of O(log N), where N is the number of digits in the input integer, and a space complexity of O(log N) due to the conversion of the integer to a string. However, the space complexity can be considered constant in practice, as the length of the string representation is limited for typical integer values.