DEV Community

Cover image for 1. Check For Palindrome Number
Ashis Kumar Pradhan
Ashis Kumar Pradhan

Posted on

1. Check For Palindrome Number

Palindrome meme
When you see a beautiful lady, a wow comes out of you, isn't it, or if you are scared of palindromes (Just like the image above)? Now, unconsciously you omitted a palindrome word. So, a palindrome word is a word that reads the same when you reverse it. The palindrome algorithm is used mainly in DNA sequence compression.

Now, we will see how to check whether a number is a palindrome. We will be using C++ to implement the logic. Here is the thought process:

  1. Store the original number (n) in another variable. Let's call it dup
  2. Initialize a variable with zero. Let's call it rev (to prevent garbage values).
  3. While the number n is not zero:
    1. Get the last digit and add it to the rev*10.
    2. Remove the digit from the number.
  4. After this check if rev is equal to dup or not. If yes then return true or else return false.

Code implementation:

class Solution {
public:
    bool isPalindrome(long n) {
        // -ve will never be a palindrome. ex: -121 is not equal to 121-
        if( n< 0)
            return false;
        long dup =x;
        long rev = 0;
        // loop till n is not 0. Here we don't know how long the loop will run so we are using a while loop instead of for
        while( n != 0)
        {
            // This helps us get the last digit and add it to the rev variable and the rev*10 helps maintain the place value
            rev = (rev* 10) + (n%10);
            // Remove the last digit from the number `n`
            n = n/10;

        }

        return rev == dup;

    }
};

Enter fullscreen mode Exit fullscreen mode

Now, time to talk about the time and space complexity. I will leave it to you to come up with the answers!

Top comments (0)