How many IP addresses are available in IPv6
June 11, 2012
Print all interleavings of two strings
June 11, 2012

Check if a number is a palindrome

Given an integer, write code to check if it is a palindrome or not. For example: 24342 is a palindrome but 32767 is not a palindrome.
The signature of the function may be as shown below:

/** Function returns 1 is num is palindrome and returns 0 otherwise.
 */
int checkPalindrome(int num);

Solution:
Algorithm:

Step 1.  First keep the modulus(absolute value) of the number. This is to make the code work for -ve integers also.
Step 2.  Reverse the digits of the number and store it in another integer.
Step 3.  Compare the two int (original & reversed). If they are equal, return 1, else 0.

Code:

int checkPalindrome(int num)
{
    int rev=0;         // To store the reversed num
    // Taking the absolute value
    if(num < 0)
      num = -num;
    // because n will change while reversing it
    int n = num;
    while(n > 0)
    {
       rev *= 10;
       rev = rev + n % 10;
       n = n/10;
    }
    if(num == rev)
       return 1;
    else
       return 0;
 }

Please let me know your feedback..
——————————————————–

Leave a Reply

Your email address will not be published. Required fields are marked *