Check If Input Number is Palindrome in Java
There are some numbers in mathematics when even reversed remain the same. Well as for observing these numbers with human eyes we don’t need to exert too much stress on our brains. However, to find the same thing using a computer program is quite a challenge for newbie programmers. Such numbers when even reversed remain the same are known as Palindrome numbers. And in today’s article, we’ll try to find Palindrome numbers using programs. So let’s find out how to Check If the Input Number is Palindrome or not in Java.
What’s The Approach?
- The simplest approach we will apply is to reverse the given input number and check if it is equal to the original number.
- Let’s consider input number
n
. Therefore if thereverse of n
is similar ton
we’ll print true otherwise we’ll print false.
- We will create a separate function to return the reverse of input n.
- Create a reverse variable
rev_num
, we will multiply it by 10 & perform a modulo operation with 10.
- The above instructions will keep executing till the value of
num
is greater than 0. So after that, we’lldivide num with 10
. This way we’ll get the trailing digit of inputn
becoming the leading digit in our reverse variable.
Also Read: How To Reverse A String in Java Using ByteArray?
Java Program To Check If Input Number is Palindrome
Input:
N=2002
Output:
Is 2002 a Palindrome number? -> true
// Java program to check whether a number // is Palindrome or not. class TechDecodeTutorials { /* Iterative function to reverse digits of num*/ static int reverseDigits(int num) { int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } /* Function to check if n is Palindrome*/ static int isPalindrome(int n) { // get the reverse of n int rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0; } /*Driver code*/ public static void main(String []args) { int n; n = 2002; System.out.println("Is " + n + " a Palindrome number? -> " + (isPalindrome(n) == 1 ? "true" : "false")); } }