Last active
October 2, 2019 10:59
-
-
Save ChrisLeNeve/ffa686d4f81d5009faa6a41f7f0d14ef to your computer and use it in GitHub Desktop.
Project Euler 4: largest palindrome
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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