Palindrome Number
Given - number n.
Return n is palindrome or not.
Steps
- Create a temporary variable to store the incoming number for later.
- Create a variable to store the reconstructed reverse of the given number and initialize it to 0.
- We take the idea of dividing (%) a number by 10 that gives the units digit as remainder. (Main step to
remember while answering problems like this)
- So, we keep a condition in while loop that number must not be 0.
- In while loop we take a temporary variable to store the unit's digit of the given number (this will be
updated at end of loop)
- Now use the temp var like below
- reverseNumber = reverseNumber * 10 + temporaryVariable
- At the end of loop we divide the given number n / 10 and update it to n, i.e n = n/10. We do this until
we reach 0 and exit the loop.
- After that we can check whether the reverseNumber == n to return boolean value.
Java Implementation
class Solution {
public boolean isPalindrome(int x) {
int temp = x;
int reverseNumber = 0;
if (x < 0) {
return false;
}
while (x != 0) {
int zeroUnitDigit = x % 10;
reverseNumber = reverseNumber * 10 + zeroUnitDigit;
x = x / 10;
}
return (reverseNumber == temp) ? true : false;
}
}