Last active
December 16, 2015 20:19
-
-
Save danielgpm/5492101 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.io.BufferedReader; | |
import java.io.FileReader; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
public class JavaPalindrome2 { | |
public static void main(String[] args) throws Exception { | |
String line = ""; | |
Long ini = System.currentTimeMillis(); | |
BufferedReader reader = new BufferedReader(new FileReader("seed.txt")); | |
int totalPalindromes = 0; | |
ArrayList<Integer> rangosMinimos = new ArrayList<Integer>(); | |
ArrayList<Integer> rangosMaximos = new ArrayList<Integer>(); | |
while ((line = reader.readLine()) != null) { | |
String[] rango = line.split(" "); | |
rangosMinimos.add(Integer.parseInt(rango[0])); | |
rangosMaximos.add(Integer.parseInt(rango[1])); | |
} | |
Collections.sort(rangosMinimos); | |
Collections.sort(rangosMaximos); | |
int maxRango = rangosMaximos.get(rangosMaximos.size() - 1); | |
for (int num = rangosMinimos.get(0); num <= maxRango; num++) { | |
if (isPalindrome(num)) { | |
for (int i = 0; i < rangosMinimos.size(); i++) { | |
int valRangoIni = rangosMinimos.get(i); | |
int valRangoFinal = rangosMaximos.get(i); | |
if ((num >= valRangoIni) && (num <= valRangoFinal)) { | |
totalPalindromes++; | |
} | |
} | |
} | |
} | |
System.out.format("Total Palindromes: %d\n ", totalPalindromes); | |
System.out.format("Duracion: %f\n", (System.currentTimeMillis() - ini) / 1000.0); | |
} | |
private static final boolean isPalindrome(int num) { | |
String sNum = Integer.toString(num); | |
for (int i = 0; i < sNum.length() / 2; i++) { | |
if (sNum.charAt(i) != sNum.charAt(sNum.length() - i - 1)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment