Java Palindrome of a Number
I have given here Java code to find out whether a given number is a palindrome or not.
Source Code
import java.lang.*;
import java.util.*;
import java.io.*;
class NumberPalindrome
{
public static String ReadString()
{
try
{
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
return reader.readLine();
}
catch (Exception e)
{
e.printStackTrace();
return "";
}
}
public static int ReadInteger()
{
try
{
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
return Integer.parseInt(reader.readLine());
}
catch (Exception e)
{
e.printStackTrace();
return 0;
}
}
public static void main(String[] args)
{
System.out.println("\nProgram to check whether given number is palindrome or not. Enter -1 to exit");
while(true)
{
System.out.print("Enter a Number (-1 to exit): ");
int n = ReadInteger();
if(n < 0)
break;
int number = n;
int index = 0;
boolean palindrome = true;
int [] digits = new int [10];
do
{
digits[index] = n % 10;
index++;
n = n / 10;
} while(n > 0);
for(int i = 0; i < index / 2 + 1; i++)
{
if(digits[i] != digits[index - 1 - i])
{
palindrome = false;
break;
}
}
if (palindrome == true)
System.out.format("The number %d is a palindrome\n", number);
else
System.out.format("The number %d is NOT a palindrome\n", number);
}
}
}
Output
|