Sunday, July 8, 2012

Palindrome Checking Algorithm in ANSI C

A palindrome is a number or a string who after being reversed is equal to its original form.

Example: mom, dad, 123321

1.Checking if a Number is a Palindrome
The algorithm for checking if a number is a palindrome is:
1)Create a copy of the number
2)Using that copy, build the reverse of the number
3)If the reverse of the number is equal to the original number, then the number is a palindrome

Here's an implementation of the number palindrome check:
/*
 * Description:
 *  Checks if a integer is a palindrome
 * Parameters:
 *  number - the integer who is going to be verified
 * Returns:
 *  true - the integer is a palindrome
 *  false - the integer is not a palindrome
 */
bool IntegerIsPalindrome(int number)
{
   int copy = number;
   int reverseNumber = 0;
   while(copy!=0)
   {
      reverseNumber= reverseNumber*10 + copy%10;
      copy/=10;
   }
   return (number==reverseNumber);
}
2.Checking if a String is a Palindrome
The algorithm for checking if a string is a palindrome is:
1)Assume that the string is a palindrome
2)Compare the first character with the last character, the second character and character before the last character and so on until you hit the middle of the string.
3)If any of the pairs compared are not equal, the string is not a palindrome.
/*
 * Description:
 *  Checks if a string is a palindrome
 * Parameters:
 *  string - the string who is going to be verified
 * Returns:
 *  true - the string is a palindrome
 *  false - the string is not a palindrome
 */
bool StringIsPalindrome(const char* string)
{
   int length = strlen(string);
   int i;
   bool isPalindrome = true;
   for(i = 0; i<(length/2); i++)
   {
      if(string[i]!=string[length-i-1])
      {
         isPalindrome = false;
         break;
      }
   }
   return isPalindrome;
}
3.Example
/*Example*/
int main(void)
{
   printf("%d %d %d\n",StringIsPalindrome("ABAABA"),
           StringIsPalindrome("MoM"),
           StringIsPalindrome("Camus"));
   printf("%d %d %d\n",IntegerIsPalindrome(-121),
           IntegerIsPalindrome(121),
           IntegerIsPalindrome(334));
   return 0;
}
/*Output
1 1 0
1 1 0
 */
Note:
Do not forget to include the headers: <stdbool.h> is needed for both functions and <string.h> is needed for the string palindrome checking function.

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger