728x90
반응형
이번 문제를 풀어 보고 싶다면? 아래 링크를 클릭하세요!
나의 경우 for 반복문을 1부터 n까지 돌면서 홀수 자리에는 정답 문자열에 '수'를 더하고, 짝수 자리에는 '박'을 더하는 식으로 풀었다.
다른 사람의 풀이를 참고했더니 reapeat()와 substring() 메서드를 통해서도 풀 수 있었다. reapeat() 메서드는 매개변수로 주어진 숫자만큼 참조 문자열을 반복한다. 예를 들어 매개변수로 3이 주어진다면 문자열은 '수박수박수박'과 같이 되어 여기서 substring() 메서드로 인덱스 0부터 n - 1까지의 숫자를 잘라내어 반환하는 것이다.
Solutions
function solution(n) { /* My Solution */ let answer = ''; for (let i = 1; i <= n; i++) { if (i % 2 === 1) answer += '수'; else if (i % 2 === 0) answer += '박'; } return answer; /* substring() Ver. */ return '수박'.repeat(n).substring(0, n); }
함께 보기
String.prototype.repeat() - JavaScript | MDN
The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.
developer.mozilla.org
String.prototype.substring() - JavaScript | MDN
The substring() method returns the part of the string between the start and end indexes, or to the end of the string.
developer.mozilla.org
728x90
반응형
'👩💻 Programming > Coding Test 문제 풀이' 카테고리의 다른 글
[Programmers] level 1: 시저 암호 by JavaScript (0) | 2022.07.10 |
---|---|
[Programmers] level 1: 문자열을 정수로 바꾸기 by JavaScript (0) | 2022.07.10 |
[Programmers] level 1: 소수 찾기 by JavaScript (0) | 2022.07.10 |
[Programmers] level 1: 서울에서 김서방 찾기 by JavaScript (0) | 2022.07.09 |
[Programmers] level 1: 문자열 다루기 기본 by JavaScript (0) | 2022.07.09 |
댓글