I know my isPalindrome method works because when i plug in 906609 it returns true, and i know that my Problem4 method at some point multiplies 993 and 913 together, which yields 906609, but for some reason it waits until 580085 to return the number. What am I doing wrong? I just can't get it to work :(
public static boolean isPalindrome(int number){
//checks to see if a number is a palendrome. (can't start with 0)
String numstring = Integer.toString(number);
char[] strarr = new char[String.valueOf(number).length()+1];
int x = 0;
int y = String.valueOf(number).length()-1;
for (int i=0;i<y+1;i++){
strarr[i] = numstring.charAt(i);
}
for (int a=0;a<String.valueOf(number).length()-1;a++){
if (strarr[x]!=strarr[y]){
return(false);
}
x++;
y--;
}
return(true);
}
public static int Problem4(){
int pp = 0;
for (int i=999;i>100;i--){
for (int j=999;j>100;j--){
pp = i*j;
if (isPalindrome(pp)){
return(pp);
}
}
}
return(pp);
}
I've tested isPalindrome with many other numbers to make sure it was functioning properly. Why doesn't it catch the answer? I'm iterating backwards, so it should get the largest palindrome first...
SOLVED: I just had to make sure that the loop was allowed to reach the highest possible palindrome by returning at the end instead and changing the value of variable a to ensure it is the highest palindrome.
public static int Problem4(){
int pp = 0;
int a = 0;
for (int i=100;i<1000;i++){
for (int j=100;j<1000;j++){
pp = i*j;
if (isPalindrome(pp)){
if (pp>a){
a = pp;
}
}
}
}
return(a);
}
If you add a print statement like this:
if (isPalindrome(pp)) {
System.out.format("i = %d, j = %d%n", i, j);
return (pp);
}
you get the result:
i = 995, j = 583
580085
So, your program never comes to 993 * 913
.