Project Euler – Problem 4 Solution (Java)

http://projecteuler.net/index.php?section=problems&id=4

	/* Project Euler - Problem 4 (http://projecteuler.net/index.php?section=problems&id=4)
	 *
	 * I was able to reduce some of the iterations by setting up the loops to not repeat
	 * computations (ie, don't do 998 x 912 and 912 * 998), but this is basically a
	 * brute force solution.
	 */
	public static void p4(){
		int pal = 0;

		for(int i=1; i<=999; i++)
			for(int j=1; j<=i; j++)
				if(i*j>pal && isPalindrome(Integer.toString(i*j)))
					pal = i*j;

		System.out.println(pal);
	}

	public static boolean isPalindrome(String str){
		int start = 0;
		int end = str.length() - 1;

		while(start < end){
			if(str.charAt(start) == str.charAt(end)){
				start++;
				end--;
			}
			else return false;
		}

		return true;
	}

No Comments »

Tina on January 28th 2009 in Project Euler

Trackback URI | Comments RSS

Leave a Reply