Skip to content

Instantly share code, notes, and snippets.

@ChrisLeNeve
Last active October 2, 2019 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisLeNeve/ffa686d4f81d5009faa6a41f7f0d14ef to your computer and use it in GitHub Desktop.
Save ChrisLeNeve/ffa686d4f81d5009faa6a41f7f0d14ef to your computer and use it in GitHub Desktop.
Project Euler 4: largest palindrome
import java.util.TreeSet;
class Scratch {
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
int solution = findLargestPalindrome();
System.out.println(solution);
}
private static int findLargestPalindrome() {
TreeSet<Integer> possibles = new TreeSet<>();
for (int i = 999; i >= 100; i--) {
for (int j = i; j >= 100; j--) {
if (isPalindrome(i * j)) {
possibles.add(i * j);
break;
}
}
}
return possibles.last();
}
private static boolean isPalindrome(int i) {
sb.setLength(0);
String s = Integer.toString(i);
// Reusing the same SB is more optimised than creating a new one, takes some load off GC
String reverse = sb.append(s).reverse().toString();
return s.equals(reverse);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment