Java solution to 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.

Running time: 5ms

Assessment: Despite finishing quickly, this is a bad solution, because it returns the first time it reaches a palindrome. The problem is that there’s no guarantee that the return value is, in fact, the correct answer. Using different input criteria could easily break it. It so happens that the returned value of this code is correct, but this was more luck than skill.

public class Problem004
	private static int createPalindrome()
		int total = 0;
		for (int i = 999; i >= 900; i--)
			for (int j = 999; j >= 900; j--)
				total = i * j;
				String s = Integer.toString(total);
				String s2 = new StringBuffer(s).reverse().toString();
				if (s.equals(s2))
					return total;
		return 0;
	public static void main(String[] args)
		long begin = System.currentTimeMillis();
		int answer = createPalindrome();
		long end = System.currentTimeMillis();
		System.out.println(end-begin + "ms");

2 thoughts on “Java solution to Project Euler Problem 4

  1. @google-c90927c8591968fe145034e6c8521079:disqus , he must have either guessed or something because I started both of mine at 999 and implemented it this way and the correct answer was the second, not the first answer to pop up. So I had a “largest” variable keep track of that.

Leave a Reply

Your email address will not be published. Required fields are marked *