https://programmers.co.kr/learn/courses/30/lessons/42839
코딩테스트 연습 - 소수 찾기
한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다. 각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때, 종이
programmers.co.kr
문제 설명 :
종이 조각에 적힌 숫자로 만들 수 있는 소수가 몇 개인지 세기
문제 풀이 :
숫자를 조합하기 위해서 순열을 이용하였습니다.
순열로 뽑은 숫자가 소수인지 아닌지 판단하여 Set에 넣어주었습니다.
Set은 중복이 되지 않는 특징이 있습니다. 그래서 Set 길이가 정답이 됩니다.
import java.util.*;
import java.util.HashSet;
import java.util.Set;
class Solution {
static int[] arr,output;
static boolean[] visited;
static String s="";
static Set<Integer> set = new HashSet();
public int solution(String numbers) {
int answer = 0;
int n = numbers.length();
arr = new int[n];
output = new int[n];
visited = new boolean[n];
for(int i = 0; i< n; i++){
char c = numbers.charAt(i);
arr[i] = c-48;
}
//순열
int count = 1;
while(count<=n){
perm(0,n,count);
count++;
}
answer= set.size();
return answer;
}
public static void perm(int depth, int n, int r){
s="";
if(depth==r){
for(int i = 0; i<r; i++){
s+=output[i];
}
int num = Integer.parseInt(s);
if(check(num)){ //소수판별
set.add(num);
}
return;
}
for(int i = 0; i<n; i++){
if(!visited[i]){
visited[i] = true;
output[depth] = arr[i];
perm(depth+1,n,r);
visited[i] = false;
}
}
}
public static boolean check(int n){
int num = n;
boolean isPrime = true;
if(num<=1) isPrime = false;
if(num>1){
for(int i = 2; i<num; i++){
if(num%i==0){
isPrime = false;
break;
}
}
}
return isPrime;
}
}
'ALGORITHM > 프로그래머스 | 백준 | 삼성 | 카카오' 카테고리의 다른 글
[프로그래머스] 폰켓몬 java (0) | 2021.06.22 |
---|---|
[프로그래머스] 로또의 최고 순위와 최저 순위 java (0) | 2021.06.13 |
[백준] 2493번 탑 java (0) | 2021.05.06 |
[프로그래머스] 구명보트 (0) | 2021.05.05 |
[백준] 1795번 암호 만들기 java (0) | 2021.05.04 |