Dear Friends:
As much as strings, some numbers are also palindrome. For instance: 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, ... , 101, 111, ... ,753537, ... and so on.
Here is the thing, We need to figure a way to find first 10.000 palindromic numbers in order to respond user's entry. Starts from 1 to 10000th palindromic number. For example if user enters 12 it means what is the 12th palindromic number between 1 and 10.000 ?
The input consists of a series of lines with each line containing one integer value i (1 <= i <= 10000). This integer value i indicates the index of the palindrome number that is to be written to the output, where index 1 stands for the first palindrome number (1), index 2 stands for the second palindrome number (2) and so on.
EX:
Input 1 --> Output should be: 1
Input 12 --> Output should be: 33
Input 24 --> Output should be: 151
import java.util.Scanner;
public class xth_palindrome
{
// Some Code may be here
public static void main(String[] args)
{
@SuppressWarnings("resource")
Scanner read = new Scanner(System.in);
System.out.println("Enter values as much as you want. To stop Enter \"0\" ");
int Xth;
do
{
Xth = read.nextInt();
// Some coding here
System.out.println(Xth + " palindromic num is " + "????");
} while(Xth != 0);
}
}
Maybe not "the very best way", but works fine.
And it does the job in less than 1 sec (depending of your hardware).
I've tested here.
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
Scanner read = new Scanner(System.in);
System.out.println("Enter values as much as you want (lower than 100000).\n To stop Enter \"0\" ");
int Xth;
do
{
Xth = read.nextInt();
// Some coding here
if (Xth > 100000)
{
System.out.println("Type a number lower than 100000");
continue;
}
int count = 0;
for (int i = 1; i <= 1000000000; i++)
{
if (!isPalindrome(i))
continue;
count++;
if (count == Xth)
{
System.out.println(Xth + "th palindromic number is " + i);
break;
}
}
if (count != Xth)
System.out.println("I can't compute that!");
} while(Xth != 0);
}
private static StringBuilder sb = new StringBuilder();
private static boolean isPalindrome(int i)
{
sb.setLength(0);
sb.append(i);
return sb.toString().equals(sb.reverse().toString());
}