Java Implementation of Problem 4

View source code here on GitHub!

public class p0004 implements IEuler
Object answer()
Returns:

The answer to Project Euler problem 4

 1/*
 2Project Euler Problem 4
 3
 4I couldn't figure out how to do this as efficiently as I would have liked. I am
 5SURE that there is a better way to check if a number is a palindrome, but I
 6could not think of one.
 7
 8Problem:
 9
10A palindromic number reads the same both ways. The largest palindrome made from
11the product of two 2-digit numbers is 9009 = 91 × 99.
12
13Find the largest palindrome made from the product of two 3-digit numbers.
14*/
15package euler;
16
17public class p0004 implements IEuler {
18    private boolean IsPalindrome(int x) {
19        String rep = Integer.toString(x);
20        int length = rep.length();
21        for (int i = 0; i < length; i++)
22            if (rep.charAt(i) != rep.charAt(length - i - 1))
23                return false;
24        return true;
25    }
26
27    @Override
28    public Object answer() {
29        int answer = 0;
30        for (int v = 101; v < 1000; v++)
31            for (int u = 100; u < v; u++) {
32                int p = u * v;
33                if (IsPalindrome(p) && p > answer)
34                    answer = p;
35            }
36
37        return answer;
38    }
39}

Tags: palindrome