Search code examples
cwhile-loopnumbersreversepalindrome

Printing 0110 as palindrome


#include <stdio.h>

int main()
{
   int n, reverse = 0, temp;

   printf("Enter a number to check if it is a palindrome or not\n");
   scanf("%d",&n);

   temp = n;

   while( temp != 0 )
   {
      reverse = reverse * 10;
      reverse = reverse + temp%10;
      temp = temp/10;
   }

   if ( n == reverse )
      printf("%d is a palindrome number.\n", n);
   else
      printf("%d is not a palindrome number.\n", n);

   return 0;
}

The above code will check whether a number is palindrome or not.It work fine.If you input 151 it will say it is a palindrome number.However if you input 0110 it will print not palindrome.Although i know 0110 is actually 110,but my professor says what to do which will print numbers like 011 and 001100 as palindrome.What to do any idea?


Solution

  • You can store the input using a string (array of chars). I have updated your code to use the same -

    #include <stdio.h>
    #include <stdlib.h>
    
    int get_len (char *inp) {
       int curr_len = 0;
       for (curr_len=0; inp[curr_len] != '\0'; curr_len++);
       return curr_len-1;
    }
    
    int main()
    {
       int palindrome = 1;
       char *inp = (char *) malloc (100*sizeof(char *));
    
       printf("Enter a number to check if it is a palindrome or not\n");
       scanf("%s",inp);
    
       int len = get_len (inp);
       int i;
       for (i=0; i < len/2; i++) 
       {
          if (inp[i] != inp[len-i]) {
            palindrome = 0;
            break;
          }
       }
    
       if ( palindrome )
          printf("%s is a palindrome number.\n", inp);
       else
          printf("%s is not a palindrome number.\n", inp);
    
       return 0;
    }