Palindrome numbers are those numbers that remain the same even after reversing the order of their digits. In this article, we will learn how to check whether the given number is a palindrome number using C program.
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.
In C, we can check if a given number is palindrome or not by using two different methods given below:
By Reversing and Comparing
A simple method for this problem is to first reverse all the digits of a given number and then compare the reverse of the number with a given number. If both are the same, then 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
Using Two Pointers and String Conversion
In this method we first need to convert the number into a string and then use the two pointers technique where the first pointer is pointing at the start of the string and the other at the end of the string. Now, we compare the characters they point to while moving these pointers towards each other. If all the characters match by the time pointers meets, the number is a palindrome, otherwise it is not.
#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