Monday, June 15, 2009

Project Euler Problem 4

Problem 4

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.

Find the largest palindrome made from the product of two 3-digit numbers.

The solution is to multiply each three digit number and check if its a palindrome or not.


public class ProblemFour {
public static void main(String[] args) {
int palindrome = 9009;

for (int i = 999; i > 99; --i) {
for (int j = i; j > 99; --j) {
int product = i * j;

if (isPalindrome(String.valueOf(product)) &&
(product > palindrome)) {
palindrome = product;
}
}
}

System.out.println(palindrome);
}

public static boolean isPalindrome(String data) {
char[] array = data.toCharArray();
int reverseIndex = array.length - 1;
int index = 0;

while (index < reverseIndex) {
if (array[index] != array[reverseIndex]) {
return false;
}

++index;
--reverseIndex;
}

return true;
}
}

No comments:

Post a Comment