Palindrome number in java
Today’s programming problem is to determine whether or not a given number is a palindrom. The program must be able to return true if the number is a palindrome and false if it is not.
Example:
Input: x = 121
Output: trueInput: x = 123
Output: false
For those who are unfamiliar with the term “palindrome number," it is a number that remains the same when its digits are reversed.
To solve this problem, we must reverse the given number and see if the reversed number equals the given number. We’ll write two functions to find the reverse and check the palindrome.
Solution:
class Solution {
//function to check the palindrome
public boolean isPalindrome(int x) {
//create rev variable to store the reverse number
// and call reverseNum function
int rev = reverseNum(x);
//Checkif the given number is equal to reverse number
if(rev==x){
//If they are equal then the number is palindrome
// So, return true
return true;
}
//Else the number is not a palindrome
//So, return false
else return false;
}
//function to reverse the number
public int reverseNum(int x){
int sum=0;
int r;
//Reverse the number
while (x>0){
r = x%10;
sum = (sum*10) + r;
x=x/10;
}
return sum;
}
}
Note:
The technique we are using to reverse the number is,
- Take number’s modulo by 10 and take it as remainder
- Initialize reversed number as 0
- Multilpy reversed number by 10 and add remainder to get new reversed number
- Divide the number by 10
- Repeat these steps until the number becomes 0