1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| public int solution(String numbers) { char[] tochar = numbers.toCharArray();
int numbersLength = tochar.length;
Set<Integer> numberSet = new HashSet<Integer>(); for (int i = 1; i <= numbersLength; i++) { perm(tochar, 0, i, numberSet); }
int answer = getPrimeCount(numberSet);
return answer; }
private void perm(char[] array, int depth, int length, Set<Integer> numberSet) { if (depth == length) {
StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { sb.append(array[i]); }
int number = Integer.parseInt(sb.toString()); if (number > 1) { numberSet.add(number); }
return; }
for (int i = depth; i < array.length; i++) { swap(array, i, depth); perm(array, depth + 1, length, numberSet); swap(array, i, depth); } }
private void swap(char[] arrary, int i, int j) { char temp = arrary[i]; arrary[i] = arrary[j]; arrary[j] = temp; }
private int getPrimeCount(Set<Integer> numberSet) { int result = 0; for (int i : numberSet) { boolean isPrime = true;
for (int j = 2; j * j <= i; j++) { if (i % j == 0) { isPrime = false; break; } }
if (isPrime) { ++result; } }
return result; }
|