Carebear - 23 days ago 6x

Java Question

I am having a bit of trouble solving Project Euler question 4. I am inexperienced in programming and didn't really understand other answers. I managed to write a code that prints all six-digits palindromes. How do I find the largest palindrome made from the multiplying of two 3-digit numbers?

`public class Main {`

public static void main(String[] args) {

int num = 998001;

int count=0;

int temp1, temp2, temp3, temp4, temp5, temp6;

int temp;

int num1=999;

int num2=100;

for (int i = 100000; i <= 998001; i++) {

num=998001-count;

temp=num;

temp1=temp%10;

temp=temp/10;

temp2=temp%10;

temp=temp/10;

temp3=temp%10;

temp=temp/10;

temp4=temp%10;

temp=temp/10;

temp5=temp%10;

temp=temp/10;

temp6=temp%10;

temp=temp/10;

if (temp1==temp6 && temp5==temp2 && temp3==temp4) {

System.out.println(num);

}

count=count+1;

}

}

}

Answer

Here is a method which loops over all numbers from 1-999 and multiplies them with all possible numbers from 1-999. You will need to define a method `isPalindrome(int)`

that will check if a given int is a palindrome.

```
//save the largest number
int largest = 0;
//loop over every possible product of numbers from 100-999
for (int i = 999; i >= 100; i--) {
for (int j = i; j >= 100; j--) {
int curr = i * j;
//if the current number is a palindrome and is greater than the last found largest
if (isPalindrome(curr) && curr > largest) {
//save it as the new largest found number
largest = curr;
}
}
}
```

The `isPalindrome`

method might look like this:

```
private static boolean isPalindrome(Integer possible) {
String toStr = possible.toString();
int len = toStr.length();
if (len % 2 == 1) {
len = len - 1;
}
for (int i = 0; i < len / 2; i++) {
if (toStr.charAt(i) != toStr.charAt(toStr.length() - (1 + i))) {
return false;
}
}
return true;
}
```

Source (Stackoverflow)

Comments