How to Check Whether a Number is Palindrome or Not

Here we need to check if the given number is a Palindrome or not. We just need to reverses the digits of the input number using a loop. Then, if the resulting reversed number is equal to the input number , then it is a Palindrome otherwise not. The following is an example of a Palindrome number.

Algorithm:

1. Loop until the input number become 0.
	
	1.1 remainder = number % 10;
	1.2 reverse = reverse * 10 + remainder;
	1.3 number = number / 10;
	
2. Return reverse when the loop breaks. That means number became 0.

Check some steps to clarify about the strategy of the algorithm:

Step 1 :

number = 17871
remainder = 0
reverse = 0
remainder = number % 10 =>  remainder = 17871 % 10 = 1
reverse = reverse * 10 + remainder => reverse = 0 * 10 + 1 = 1
number = number / 10 => number = 17871 / 10 = 1787

Step 2 :

number = 1787
remainder = 1
reverse = 1
remainder = number % 10 =>  remainder = 1787 % 10 = 7
reverse = reverse * 10 + remainder => reverse = 1 * 10 + 7 = 17
number = number / 10 => number = 1787 / 10 = 178

Now let us implement the same:

public class PalindromeNumber {

	public static int getReverse(int number) {

		int reverse = 0;
		int remainder = 0;
		while (number > 0) {
			remainder = number % 10;
			reverse = reverse * 10 + remainder;
			number = number / 10;
		}
		return reverse;
	}

	public static void main(String args[]) {
		int inNumber = 1771;
		int reverse = getReverse(inNumber);
		System.out.println("Checking for inNumber >> " + inNumber);
		if (inNumber == reverse) {
			System.out.println("It is a Palindrome.");
		} else {
			System.out.println("It is not a Palindrome.");
		}
		System.out.println("==============================");
		inNumber = 17;
		reverse = getReverse(inNumber);
		System.out.println("Checking for inNumber >> " + inNumber);
		if (inNumber == reverse) {
			System.out.println("It is a Palindrome.");
		} else {
			System.out.println("It is not a Palindrome.");
		}
	}
}

Output of the program:

Checking for inNumber >> 1771
It is a Palindrome.
==============================
Checking for inNumber >> 17
It is not a Palindrome.

 

core java 12 Algorithm 12 Google 12

FOLLOW US ON LinkedIn



Explore Tutu'rself