A palindrome number remains the same when its digits are reversed. Palindrome numbers can be identified by comparing the original number with its reverse or by checking their digits from both ends.
Examples
Input: 121
Output: Yes
Explanation: The number 121 remains the same when its digits are reversed.Input: 123
Output: No
Explanation: The number 123 does not remain the same when its digits are reversed.
Approaches to Check Palindrome Number
We can check whether a number is a palindrome using the following approaches:
1. By Reversing and Comparing
We reverse the digits of the number and compare the reversed number with the original number. If both are equal, the number is a palindrome.
#include <stdio.h>
int reverseNum(int N) {
// Function to store the reversed number
int rev = 0;
while (N > 0) {
// Extract the last digit
int dig = N % 10;
// Append the digit to the reversed number
rev = rev * 10 + dig;
// Remove the last digit
N /= 10;
}
return rev;
}
int isPalindrome(int N) {
// Negative numbers are not palindromes
if (N < 0)
return 0;
return N == reverseNum(N);
}
int main() {
int N = 121;
if (isPalindrome(N)) {
printf("Yes\n");
}
else {
printf("No\n");
}
return 0;
}
Output
Yes
Explanation
- reverseNum() extracts each digit using % 10 and builds the reversed number.
- isPalindrome() compares the original number with its reverse.
- If both are equal, it returns 1; otherwise, it returns 0.
2. Using Two Pointers and String Conversion
In this approach, the number is converted into a string. Two pointers start from opposite ends and compare characters while moving toward the center.
#include <stdio.h>
#include <string.h>
int isPalindrome(int n) {
char str[20];
// Convert the number to a string
sprintf(str, "%d", n);
// Left pointer starting from the first character
int left = 0;
// Right pointer starting from the last character
int right = strlen(str) - 1;
// Loop until the pointers meet in the middle
while (left < right) {
// If mismatch is found (not a palindrome)
if (str[left] != str[right]) {
return 0;
}
// Move pointers towards each other
left++;
right--;
}
return 1;
}
int main() {
int num = 1221;
// Check if the number is a palindrome and print the result
if (isPalindrome(num)) {
printf("Yes\n");
}
else {
printf("No\n");
}
return 0;
}
Output
Yes
Explanation
- sprintf() converts the number into a string.
- left and right point to the first and last characters.
- If any pair of characters differs, the number is not a palindrome.
- If all pairs match, the number is a palindrome.