我試圖從SPOJ解決問題。但對我來說問題並不在於算法的實際難度;這是我的Java代碼的性能,因爲它通常會導致超時錯誤的時間限制。我聽說Java比C/C++在競賽問題上的表現慢,這是臭名昭着的;但是,我現在可以編寫的唯一語言是Java。因此,我在尋求建議,使我的代碼更加整潔,速度更快。以下是我的解決方案和源代碼問題。需要固定我的Java代碼
public class NextPalindrome {
public static BigInteger secondHalf(BigInteger b) {
String s = b.toString();
int n = s.length();
if(n==1){
return b;
}
String end = s.substring((n + 1)/2, n);
BigInteger End = new BigInteger(end);
return End;
}
public static BigInteger reverse(BigInteger b) {
String s = b.toString();
int n = s.length();
String beg = b.toString();
String reversebeg = "";
while (true) {
for (int i = n - 1; i >= 0; i--) {
reversebeg = reversebeg + beg.charAt(i);
}
break;
}
BigInteger reverse = new BigInteger(reversebeg);
return reverse;
}
public static BigInteger firstHalf(BigInteger b) {
String s = b.toString();
int n = s.length();
if(n==1){
return b;
}
String beg = s.substring(0, n/2);
BigInteger Beg = new BigInteger(beg);
return Beg;
}
public static BigInteger nextPalindrom(BigInteger b) {
String s = b.toString();
int n = s.length();
if(n==1){
if(b.equals(9)){
return BigInteger.valueOf(11);
} else {
return b.add(BigInteger.valueOf(1));
}
}
if (n % 2 == 1&&n>1) {
Character c = s.charAt(n/2);
String C = c.toString();
BigInteger med = new BigInteger(C);
BigInteger beg = firstHalf(b);
BigInteger end = secondHalf(b);
if (reverse(beg).compareTo(end) <= 0) {
beg.add(BigInteger.valueOf(1));
if (med.compareTo(BigInteger.valueOf(9)) == 0) {
c = '0';
} else {
med = med.add(BigInteger.valueOf(1));
}
}
String temp = beg.toString();
String temp1 = reverse(beg).toString();
C = med.toString();
String result = temp + C;
result = result.concat(temp1);
BigInteger B = new BigInteger(result);
return B;
}
BigInteger beg = firstHalf(b);
BigInteger end = secondHalf(b);
if (reverse(beg).compareTo(end) <= 0) {
beg = beg.add(BigInteger.valueOf(1));
}
String temp = beg.toString();
String temp1 = reverse(beg).toString();
String result = temp.concat(temp1);
BigInteger B = new BigInteger(result);
return B;
}
public static void main(String[] args)throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s = in.readLine();
int N = Integer.parseInt(s);
for (int i = 0; i < N; i++) {
BigInteger big = new BigInteger(in.readLine());
BigInteger palindrom = nextPalindrom(big);
System.out.println(palindrom);
}
}
}
你的問題更適合這個網站的概念:http://codereview.stackexchange.com – Mik378
我會開始不把數字轉換成字符串。 – Blender
@Blender我沒有把字符串變成數字。 –