The “Palindrome Number” problem in C++ involves determining whether a given integer is a palindrome or not.
A palindrome number is a number that reads the same backward as forward. For example, 121 and 454 are palindrome numbers, while 123 and 456 are not.
To solve this problem, we can use a simple algorithm that involves reversing the digits of the given number and then comparing the reversed number with the original number. If they are the same, the number is a palindrome; otherwise, it’s not.
Here’s a C++ function that checks whether a given integer is a palindrome or not:
#include <iostream>
bool isPalindrome(int num) {
if (num < 0) {
// Negative numbers cannot be palindromes.
return false;
}
int original = num;
int reversed = 0;
while (num > 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
return original == reversed;
}
int main() {
int num;
std::cout << "Enter an integer: ";
std::cin >> num;
if (isPalindrome(num)) {
std::cout << num << " is a palindrome." << std::endl;
} else {
std::cout << num << " is not a palindrome." << std::endl;
}
return 0;
}
The isPalindrome
function takes an integer num
as input and returns true
if it’s a palindrome, and false
otherwise. We start by checking if the number is negative (negative numbers cannot be palindromes), and if it is, we return false
.
Next, we create two variables, original
and reversed
. We store the original number in original
to compare it later with the reversed number. We then reverse the digits of the input number num
by extracting the last digit and adding it to the reversed
variable. We repeat this process by removing the last digit from num
until num
becomes 0.
Finally, we compare the original
number with the reversed
number. If they are the same, the function returns true
, indicating that the input number is a palindrome. Otherwise, it returns false
.
This solution is optimized with a time complexity of O(log N), where N is the value of the input number. We only iterate through the digits of the number once, making it an efficient solution for checking palindrome numbers in C++.