How to check or make a number palindrome in Java

Here we will create an example on how to check a given number is palindrome or not. We will also make the given number palindrome if it is not palindrome. In our other tutorial we have seen how to check a string is palindrome or not.

A string or number is palindrome if it is equal to its reversed counterpart. For example, madam, 11, 22, etc.

Prerequisites

Java

Check or make Palindrome

Now we will check the given number is palindrome or not and at the same time we will also make the number palindrome if it is not already palindrome.

We will also keep track of how many iterations are required to make the given number palindrome.

If the number is not palindrome then we get the reverse of the number and add it to the number and this process gets continued until it becomes a palindrome.

public static int checkAndMake(int n) {
		if (String.valueOf(n).length() < 2) {
			throw new RuntimeException("Length must be at least two digits");
		}

		int rev = 0, itr = 0;

		rev = computeReverse(n);

		if (n == rev) {
			System.out.println("Iteration: " + itr);
			return rev;
		} else {
			while (true) {
				rev = computeReverse(n);

				int num = n + rev;

				n = num;

				rev = computeReverse(num);

				if (num == rev) {
					System.out.println("Iteration: " + itr);
					return rev;
				} else {
					++itr;
				}
			}
		}
	}

	private static int computeReverse(int n) {
		int reverse = 0;

		while (n != 0) {
			reverse = reverse * 10;
			reverse = reverse + n % 10;
			n = n / 10;
		}

		return reverse;
	}

Testing the Program

Now we will test our above methods:

public static void main(String[] args) {
	// checkAndMake(9);
	System.out.println(checkAndMake(10));
	System.out.println(checkAndMake(20));
	System.out.println(checkAndMake(150));
}

The above code snippets will produce the below output:

Iteration: 0
11
Iteration: 0
22
Iteration: 1
303

Download Code

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *