我应该有9秒的时间限制,但是当我在NetBeans上运行2个数字接近一百万个数字时,它需要5秒钟才能输出。我的isPalindrome方法比较对称数字(第1个和最后一个,第2个和第2个等等),并根据以下规则编辑数字:
我会按照这些规则保留我的电话号码,直到找到回文。
总结一下我的问题是:为什么在NetBeans上我的程序在给定的时间范围内运行时,为什么出现超过时间限制的错误?
公共类SPOJ5 {
/**
* @param args the command line arguments
*/
private static final String counter = "01234567890";
public static void main(String[] args) {
int t;
BigInteger addNum;
List<BigInteger> k = new ArrayList();
Scanner in = new Scanner(System.in);
do {
try {
t = Integer.parseInt(in.next());
} catch (Exception e) {
t = 2;
}
} while (t < 0);
do {
try {
addNum = new BigInteger(in.next());
addNum = addNum.add(BigInteger.ONE);
if (digitCount(addNum) < 999999) {
k.add(addNum);
}
} catch (Exception e) {
k.add(BigInteger.valueOf(9).pow(100));
}
t--;
} while (t > 0);
for (BigInteger num : k) {
int digits = digitCount(num);
int middleNum;
int count = 0;
StringBuilder number = new StringBuilder(num.toString());
if (digits % 2 == 0) {
middleNum = digits / 2;
number = new StringBuilder(num.toString());
number = isPalindrome(number, digits - 1, count, middleNum);
} else {
middleNum = digits / 2;
number = isPalindrome(number, digits - 1, count, middleNum + 1);
}
System.out.println(number);
}
}
public static StringBuilder isPalindrome(StringBuilder number, int lastDigitIndex, int firstDigitIndex, int middleNum) {
while (lastDigitIndex >= middleNum) {
if (number.charAt(firstDigitIndex) != number.charAt(lastDigitIndex)) {
if (counter.indexOf(number.charAt(firstDigitIndex)) > counter.indexOf(number.charAt(lastDigitIndex))) {
number.replace(lastDigitIndex, lastDigitIndex + 1, Character.toString(number.charAt(firstDigitIndex)));
firstDigitIndex++;
lastDigitIndex--;
} else {
number.replace(lastDigitIndex, lastDigitIndex + 1, Character.toString(number.charAt(firstDigitIndex)));
do {
number.replace(lastDigitIndex - 1, lastDigitIndex, Character.toString(counter.charAt(counter.indexOf(number.charAt(lastDigitIndex - 1)) + 1)));
lastDigitIndex--;
} while ((Character.toString(counter.charAt(counter.indexOf(number.charAt(lastDigitIndex)))).equals("0")));
lastDigitIndex = number.length() - 1;
firstDigitIndex = 0;
}
} else {
firstDigitIndex++;
lastDigitIndex--;
}
}
return number;
}
public static int digitCount(BigInteger bi) {
String s = bi.toString();
return s.length();
}
}