In: Computer Science
Java Palindrome (Timelimit: 10seconds)
Problem Description
Write a Java program to solve the following problem.
A palindromic number is an integer that is the same when the digits are reversed. For example, 121 and 625526 are palindromic, but 625 is not a palindromic number.
Input:
The input is in ‘palindrome.txt’. The first line of the input contains the line count m (1 ≤ m ≤ 1,000), which is the number of lines that follows the first line. Each of the following lines contains an integer of n digits (1 ≤ n ≤ 5,000).
Sample input:
3.
12333.
92837465.
1000000000000000123.
Output: The output consists of m lines. Each line transforms the corresponding input line into a palindrome by concatenating the input and its digits in reversed order. To minimize the output length, you must not repeat the trailing digit (or, digits if there are multiple occurrences of the same digit) of the input integer.
Sample output:
1233321.
928374656473829.
1000000000000000123210000000000000001.
Information
1. The expected complexity is O(n).
2. You can assume that the input integers are positive, and does not start with zero. Write a code ‘A.java’ that reads ‘palindrome.txt’ and writes the output in a filecalled‘A.txt’.
3. The score will be 0 if your program does not terminate within 10 seconds.
Every palindrome of 4 digits is divisible by 11 (good to know, but not related to this assignment). Can you prove it in a midterm question?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Vamsi
*/
public class Palindrome_numbers {
public static void main(String argv[]) throws
FileNotFoundException
{
Scanner scanner = new Scanner(new
File("C:/Users/Vamsi/Desktop/palindrome.txt"));//give correct
path
long t;
int i = 0;
while(scanner.hasNextLong())
//reading integers
{
t = scanner.nextLong();
if(i!=0)
{
//converting to palindrome
int k=0;
long p=-1;
long c=0;
long m = t;
long result=0;
while(0<m)//also not repeating trailing digits
{
c=m%10;
if(p==-1)
p=c;
else if(k==-1)
{
result = result*10 + c;
}
else
{
if(c!=p)
{
k=-1;
result = result*10 + c;
}
}
p=c;
m=m/10;
}
//printing output
if(result!=0)
System.out.println(t+""+result);
else
System.out.println(t);
}
i++;
}
}
}
output:
run:
1233321
928374656473829
1000000000000000123210000000000000001
BUILD SUCCESSFUL (total time: 0 seconds)