Skip to content

Instantly share code, notes, and snippets.

@goyuninfo
Last active August 29, 2015 14:01
Show Gist options
  • Save goyuninfo/ba66eae80217a5d22707 to your computer and use it in GitHub Desktop.
Save goyuninfo/ba66eae80217a5d22707 to your computer and use it in GitHub Desktop.
Project Euler Problem 4 Largest palindrome product
package euler;
/**
* @author i88.ca
*
*/
public class P4 {
public static int reverse(int number) {
// reverse function of String is applicable too.
int result = 0;
while (number != 0) {
int remainder = number % 10;
result = result * 10 + remainder;
number = number / 10;
}
return result;
}
public static boolean isPalindrome(int input) {
return reverse(input) == input;
}
public static void main(String[] args) {
int result = 0;
for (int i = 999; i >= 100; i--) {
// For example the number 69696 is checked both when i=132 and j=528
// and when i=528 and j=132.
// j<=i is applicable too
for (int j = 999; j >= i; j--) {
int r = i * j;
// stop checking i and j that would be too small to improve upon
// the largest palindrome found so far.
if (r < result)
break;
if (!isPalindrome(r)) {
continue;
} else {
result = r;
}
}
}
System.out.println(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment