Palindrome number reads the same from both directions, forward and backward. For example, “156434651” reads the same from both directions. If we reverse a palindrome number, the reversed number would be the same as the original one. Here we’ll see how to write a C program to check whether a number is a palindrome.
Method 1
int reverse_integer(int in) {
int out = 0;
while(in) {
out = out*10 + in%10;
in /= 10;
}
return out;
}
int is_palindrome(int n) {
if(n == reverse_integer(n)) return 1;
return 0;
}
Here first we reverse the number and compare that with the original one. If they are same, then the number is palindrome and the function, is_palindrome(), returns 1.
Method 2
int length(int n) {
int l = 0;
while(n) {
l++;
n /= 10;
}
return l;
}
/*Function to return the digit of n-th position of num. Position starts from 0*/
int getdigit(int num, int n)
{
int r, t1, t2;
t1 = pow(10, n+1);
r = num % t1;
if (n > 0)
{
t2 = pow(10, n);
r = r / t2;
}
return r;
}
int is_palindrome(int n) {
int len = 0, i = 0;
len = length(n);
for(i = 0; i < len/2; i++) {
if(getdigit(n, i) != getdigit(n, len - i -1)) return 0;
}
return 1;
}
Here we compare the first digit of the number with the last digit, second digit with the second last digit and so on. If any comparison fails (not equal), that means the number is not a palindrome. The function, is_palindrome(), returns 0. If all comparisons pass, it returns 1.
The getdigit() is used to get a digit of any position of a number.
The Complete Program
You can compile and run this program.
#include <stdio.h>
int reverse_integer(int in) {
int out = 0;
while(in) {
out = out*10 + in%10;
in /= 10;
}
return out;
}
int is_palindrome(int n) {
if(n == reverse_integer(n)) return 1;
return 0;
}
int main(){
int n = 0;
printf("Enter a number: ");
scanf("%d", &n);
if(is_palindrome(n)) {
printf("\"%d\" is a palindrome.\n", n);
} else {
printf("\"%d\" is not a palindrome.\n", n);
}
return 0;
}
Output of the above program:
Enter a number: 23456
"23456" is not a palindrome.
Enter a number: 5684865
"5684865" is a palindrome.