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:
- Store the original number (
n
) in another variable. Let's call itdup
- Initialize a variable with zero. Let's call it
rev
(to prevent garbage values). - While the number
n
is not zero:- Get the last digit and add it to the
rev*10
. - Remove the digit from the number.
- Get the last digit and add it to the
- After this check if
rev
is equal todup
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;
}
};
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)