Palindrome Digits

Like palindrome string we want to know if the digits of the numbers are palindrome or not. This means the digits will be a mirror image from the mid point.


Logic is simple we start extracting digits from LSB. Say the number is decimal so base will be 10. Now if we divide the number by 10 then the modulo reminder is the LSB digit and same time division result will be shifted to right. Same way again we can get next digit and shift the number right. Now as we are getting digits we can construct a new number and multiply by 10 each time in the iteration. This way the digits will be shifted left in the MSB in the new number. In this way iteration will extract LSB digit from the original number and this same digit will be pushed to the MSB of the new number. Finally we will get the digits in the reversed order in the resultant number. We can compare this number if it is same as the original number. We can modify the base 10 with base 8 for octal number or base 16 for hexadecimal number or base 2 for binary number to check if the digits are palindrome and same program logic can be reused.

Source code

#include <stdio.h>
int main(int argc, char *argv[])
  int num = 0;
  int rnum = 0, onum;
  printf ("Enter a number : " );
  scanf ("%d", &num);
  onum = num;
    rnum *= 10;
    rnum += onum % 10;
    rnum = onum /10;
  while(onum > 0);
  printf ("Original %d == Reverse %d (%s)", num, rnum, num == rnum ? "Same" : "Not Same");



Enter a number : 12345
Original 12345 == Reverse 54321 (Not Same)
Enter a number : 12321
Original 12321 == Reverse 12321 (Same)

About our authors: Team EQA

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.