|
์ฝ๋ ์์ฑํ๊ธฐ
HashSet<Integer> numberSet = new HashSet<>();
public int solution(String numbers) {
int answer = 0;
recursive("",numbers);
Iterator<Integer> it = numberSet.iterator();
while(it.hasNext()) {
int number = it.next();
if(isPrime(number))
answer++;
}
return answer;
}
public void recursive(String comb, String others) {
if (!comb.equals(""))
numberSet.add(Integer.valueOf(comb));
for (int i = 0; i < others.length(); i++) {
recursive(comb + others.charAt(i), others.substring(0, i) + others.substring(i + 1));
}
}
public boolean isPrime(int num) {
if(num == 0 || num == 1) return false;
for(int i=2; i<=(int)Math.sqrt(num); i++) {
if(num%i == 0 ) return false;
}
return true;
}
Java
๋ณต์ฌ
|
์ฝ๋ ์ค๋ช
ํ๊ธฐ
1.
์ซ์๋ค์ ์กฐํฉํ์ฌ ๋ชจ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ๋ง๋ ๋ค
a.
์ซ์์ ์กฐํฉ์ธ comb์ ๋จ์ ์ซ์๋ฅผ ๋ํ๋ด๋ others๋ฅผ ์ธ์๋ก ๊ฐ๋๋ค
b.
for๋ฌธ์ ํตํด ๋จ์ ์ซ์์ ๊ธธ์ด๋งํผ ๋ฐ๋ณตํ๋ค
c.
์ซ์ ํ๋๋ฅผ ๊บผ๋ด comb์ ์ถ๊ฐํ๊ณ ๋จ์ ์ซ์๋ฅผ ๋ํ๋ด๊ธฐ์ํด ๊บผ๋ธ์ซ์๋ฅผ ์ ์ธํ๊ณ substring์ ํ์๋ค
d.
๋ค์ ํจ์๋ฅผ ์ ์ธํ๋ค
e.
๊ทธ๋ ๊ฒ ๋ฐ๋ณตํ๋ฉด ๋ชจ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ๋ค ๋ฃ๊ฒ๋๋ค
2.
์ค๋ณต๋์ง์๊ฒ hashSet์ ๋ฃ๋๋ค
3.
๊ฐ์ ํ๋ํ๋ ๊บผ๋ด์ด ์์์ธ์ง ํ์ธํ๋ค
a.
0๊ณผ 1์ ์์๊ฐ ์๋๊ธฐ๋๋ฌธ์ ๊ทธ ์๊ฐ๋์ฌ๊ฒฝ์ฐ ๋ฐ๋ก false๋ฅผํ๋ค
b.
์์๋ ์๊ธฐ ์์ ์ ์์ ์ ๊ณฑ๊ทผ๊น์ง๋ง ๊ตฌํ๋ฉด ๋๊ธฐ๋๋ฌธ์ ์์ ์ ๊ณฑ๊ทผ๊น์ง for๋ฌธ์ ์
๋ ฅํ๋ค
c.
๊ทธ๋ฆฌ๊ณ ๋๋จธ์ง๊ฐ 0์ผ๊ฒฝ์ฐ ๋๋์ด ๋จ์ด์ง๋ ์๊ฐ ์์ผ๋ฏ๋ก false์ฒ๋ฆฌํ๋ค
d.
for๋ฌธ์ด ๋๋๋ ์์๊ฒฝ์ฐ ์์์ด๋ฏ๋ก true์ฒ๋ฆฌํ๋ค
4.
์์์ผ๊ฒฝ์ฐ answer๋ฅผ 1 ๋ํ๋ค
๋ง์ฝ 1,7,3์ด๋ผ๋ ์๊ฐ ์์๊ฒฝ์ฐ
โข
for( i < 3 ) i = 0
โฆ
comb = 1, others = 73
โช
for( i < 2 ) i = 0
โข
comb = 17, others = 3
โฆ
for( i < 1 ) i = 0
โช
comb = 173, others = โโ
โข
for๋ฌธ์ด ๋์ด๊ธฐ ๋๋ฌธ์ ๋ค์ ๋์๊ฐ๋ค
โฆ
for๋ฌธ์ด ๋์ด๊ธฐ ๋๋ฌธ์ ๋ค์ ๋์๊ฐ๋ค
โช
for( i < 2 ) i = 1
โข
comb = 13, other = 7
โฆ
for( i < 1 ) i = 0
โช
comb = 137, others = โโ
โข
for๋ฌธ์ด ๋์ด๊ธฐ ๋๋ฌธ์ ๋ค์ ๋์๊ฐ๋ค
โฆ
for๋ฌธ์ด ๋์ด๊ธฐ๋๋ฌธ์ ๋ค์ ๋์๊ฐ๋ค
โช
for๋ฌธ์ด ๋์ด๊ธฐ ๋๋ฌธ์ ๋ค์ ๋์๊ฐ๋ค
โข
for( i < 3 ) i = 1
โฆ
comb = 7, others = 13
โช
for( i < 2 ) i = 0
โข
comb = 71, other = 3
โฆ.๊ณ์ ๋ฐ๋ณต