Problem statement could be found@ https://leetcode.com/problems/palindrome-number/
Approach - Reverse the actual number and then compare it with original.If two number are same, then the given number is palindromic
Points to remember
1. Negative numbers never palindromic
2. Integer might overflow on reversal, hence it is important to store it in long variable
Following is the code snippet
class Solution {
public:
int reverse(long x, long a){
if (x==0){
return a;
}else{
a=a*10+x%10;
return reverse(x/10,a);
}
}
bool isPalindrome(int x) {
if (x<0)
return false;
long temp = x;
long y = reverse(x,0);
return (x==y);
}
};
Approach - Reverse the actual number and then compare it with original.If two number are same, then the given number is palindromic
Points to remember
1. Negative numbers never palindromic
2. Integer might overflow on reversal, hence it is important to store it in long variable
Following is the code snippet
class Solution {
public:
int reverse(long x, long a){
if (x==0){
return a;
}else{
a=a*10+x%10;
return reverse(x/10,a);
}
}
bool isPalindrome(int x) {
if (x<0)
return false;
long temp = x;
long y = reverse(x,0);
return (x==y);
}
};
No comments:
Post a Comment