728x90
๋ฐ์ํ
๐ 02 - ์ฌ๊ทํจ์๋ฅผ ์ด์ฉํ ์ด์ง์ ์ถ๋ ฅ
10์ง์ N์ด ์ ๋ ฅ๋๋ฉด 2์ง์๋ก ๋ณํํ์ฌ ์ถ๋ ฅํ๋ ๋ฌธ์ ์ด๋ค. ๋จ, ์ฌ๊ทํจ์๋ฅผ ์ด์ฉํด์ ์ถ๋ ฅํด์ผ ํ๋ค.
์ด์ง์๋ฅผ ๊ตฌํ๋ ๊ณผ์
- 1๋จ๊ณ: ๋ณํํ๋ ค๋ ์๋ฅผ 2๋ก ๋๋ ํ ๋ชซ๊ณผ ๋๋จธ์ง ๊ธฐ๋ก
- 2๋จ๊ณ: 1๋จ๊ณ์์ ๊ณ์ฐํ ๋ชซ์ 2๋ก ๋๋ ํ ๋ชซ๊ณผ ๋๋จธ์ง ๊ธฐ๋ก, ...๋ชซ์ด 0์ด ๋ ๋๊น์ง ๋ฐ๋ณต
- ๊ธฐ๋กํ ๋๋จธ์ง ๊ฐ์ ์๋์์ ์๋ก ์ฝ์ผ๋ฉด 2์ง๋ฒ์ผ๋ก ๋ณํ ์๋ฃ
๐ ํ์ด ๋ฐฉ๋ฒ
์ด์ง์๋ฅผ ๊ตฌํ๋ ๊ณผ์ ์ ๋ณด๋ฉด ๊ธฐ๋กํ ๋๋จธ์ง ๊ฐ์ ์๋์์ ์๋ก ์ฝ์ด์ผ(LIFO ๊ตฌ์กฐ) 2์ง๋ฒ์ผ๋ก ๋ณํํ ์ ์๋ค๋ ๊ฒ์ ์ ์ ์๋ค. ์ด๋ ์ฌ๊ทํจ์๋ฅผ ์ฌ์ฉํ์ฌ ๋ฌธ์ ํด๊ฒฐ์ด ๊ฐ๋ฅํ๋ค๋ ๊ฒ์ด๋ค. (์ฐธ๊ณ ) ์ฌ๊ทํจ์ ์๊ณ ๋ฆฌ์ฆ
- ๋ชซ(L)์ด 0์ด ๋ ๋๊น์ง ๊ณ์ํ์ฌ DFS() ํจ์๋ฅผ ํธ์ถํ๋๋ฐ ์ธ์๋ 2๋ก ๋๋ ๋ชซ(์ ์)์ ๋ฃ๋๋ค.
- ๋ชซ์ด 0์ด ๋์ค๋ฉด return ํ๋ค.
- ์คํ์ ์ ์ฅ๋ ํจ์๋ฅผ ์ฐจ๋ก๋๋ก ํธ์ถํ์ฌ 2๋ก ๋๋ ๋๋จธ์ง๋ฅผ answer ๋ณ์์ ๋์ ์ํจ ํ ํจ์๋ฅผ ์ข ๋ฃํ๋ค.
- ์คํ์ ์ ์ฅ๋ ์คํ ํ๋ ์์ด ๋ชจ๋ pop ๋๊ณ ๋๋ฉด answer ๋ณ์์ ์ ์ฅ๋ ๊ฐ์ ์ถ๋ ฅํ๋ค.
๐ ์์ค ์ฝ๋
function solution(n) {
let answer = '';
function DFS(L) {
if (L === 0) return;
else {
DFS(parseInt(L / 2));
answer += L % 2; // ์์ ์ค์โ DFS() ํจ์ ํธ์ถ๋ณด๋ค ์์ ์์ผ๋ฉด โ
}
}
DFS(n);
return answer;
}
console.log(solution(11));
'Algorithm > ์ธํ๋ฐ(inflearn)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JavaScript/section 8] 04 - ๋ถ๋ถ์งํฉ ๊ตฌํ๊ธฐ (0) | 2022.10.20 |
---|---|
[JavaScript/section 8] 03 - ์ด์งํธ๋ฆฌ ์ํ (0) | 2022.10.18 |
[JavaScript/section 8] 01 - ์ฌ๊ทํจ์ (0) | 2022.10.14 |
[JavaScript/section 7] 12 - ๋ง๊ตฌ๊ฐ ์ ํ๊ธฐ (0) | 2022.10.12 |
[JavaScript/section 7] 11 - ๋ฎค์ง ๋น๋์ค (0) | 2022.10.10 |