这是我到目前为止所写的。它可以编译,据我所知,它应该“工作”——如果你要给你的计算机无限的时间来计算答案!
我只是想知道是否有人可以给我一种优化它的方法,以便我的程序会告诉我通过将任意两个相乘形成的最高回文数(向前和向后都相同,例如 91 * 99 = 9009;)三位数的数字。
public class HighestPalindrome {
public static void main(String[] args) {
int number=0;
int answer=0;
search:
for(int LoopOfFirstNumber=999;LoopOfFirstNumber<=100;LoopOfFirstNumber -= 3){
for(int LoopOfSecondNumber=LoopOfFirstNumber;LoopOfSecondNumber<=100;LoopOfSecondNumber-=3)
{
number = LoopOfFirstNumber * LoopOfSecondNumber;
if (number == reverse(number))
{
answer=number;
System.out.println(answer);
break search;
}
}
}
}
//The code after this works fine, I believe. It will reverse any number given very quickly, I think the problem
//is above....with the two for loops!
private static int reverse(int n, int r) {
if (n == 0) return r;
System.out.println("This iteration returns " + n/10 + " and " + 10*r+n%10);
return reverse(n/10, 10*r+n%10);
}
public static int reverse(int n) {
return reverse(n, 0);
}