Here is a solution that doesn't iterate through all the 6-digit numbers:
public static boolean isPalindrome(int nr) {
int rev = 0; // the reversed number
int x = nr; // store the default value (it will be changed)
while (x > 0) {
rev = 10 * rev + x % 10;
x /= 10;
}
return nr == rev; // returns true if the number is palindrome
}
public static void main(String[] args) {
int max = -1;
for ( int i = 999 ; i >= 100 ; i--) {
for (int j = 999 ; j >= 100 ; j-- ) {
int p = i * j;
if ( max < p && isPalindrome(p) ) {
max = p;
}
}
}
System.out.println(max > -1? max : "No palindrome found");
}
Edit:
An improved solution for the main
method ( according to Peter Schuetze ) could be:
public static void main(String[] args) {
int max = -1;
for ( int i = 999 ; i >= 100 ; i--) {
if ( max >= i*999 ) {
break;
}
for (int j = 999 ; j >= i ; j-- ) {
int p = i * j;
if ( max < p && isPalindrome(p) ) {
max = p;
}
}
}
System.out.println(max > -1? max : "No palindrome found");
}
For this particular example, the time is about 2 times better, but if you have bigger numbers, the improvement will be more significant.
Output:
906609
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…