Share on Google+Share on Google+

Check whether the number is palindrome or not

Advertisement
In this section, you will learn how to check whether the number is palindrome or not.

Check whether the number is palindrome or not

A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction. Here we are going to check whether the number entered by the user is palindrome or not. You can check it in various ways but the simplest method is by  reversing the digits of the original number and check to see if the reversed number is equal to the original.

Here is the code:

import java.util.*;

public class NumberPalindrome {
	public static void main(String[] args) {
		try {
			Scanner input = new Scanner(System.in);
			System.out.print("Enter number: ");
			int num = input.nextInt();
			int n = num;
			int reversedNumber = 0;
			for (int i = 0; i <= num; i++) {
				int r = num % 10;
				num = num / 10;
				reversedNumber = reversedNumber * 10 + r;
				i = 0;
			}
			if (n == reversedNumber) {
				System.out.print("Number is palindrome!");
			} else {
				System.out.println("Number is not palindrome!");
			}
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}

Output:

Enter number:  57675
Number is palindrome!

Advertisements

Posted on: January 15, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.