본문 바로가기
문제 풀이/Programmers

[프로그래머스] 12903번: 가운데 글자 가져오기 (JavaScript)

by Electrohyun 2025. 6. 4.

 


 

생각 과정

 

문자열 길이가 홀수면 (문자열길이 / 2)번째 인덱스를 리턴하자.

-> 길이가 5인 스트링의 경우 3번째 리턴

 

문자열 길이가 짝수면 ((문자열길이 / 2) - 1)번째, (문자열길이 / 2)번째 인덱스를 리턴하자.

-> 길이가 4인 스트링의 경우 2번째, 3번째 리턴

1
2
3
4
5
6
7
8
9
10
11
12
function solution(s) {
  let answer = '';
    
  if (s.length % 2 === 0) {
    answer += s[s.length / 2 - 1];
    answer += s[s.length / 2];
  } else {
    answer += s[Math.floor(s.length / 2)];
  }
    
  return answer;
}
cs

 

알게 된 것들

 

현재 코드에서 s.length가 반복된다

-> s.length를 const wordLength = s.length; 처럼 분리하여 사용하면 가독성, 유지보수성, 의미 전달 명확성을 높일 수 있다.

 

수정한 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
function solution(s) {
  let answer = '';
  const wordLength = s.length;
    
  if (wordLength % 2 === 0) {
    answer += s[wordLength / 2 - 1];
    answer += s[wordLength / 2];
  } else {
    answer += s[Math.floor(wordLength / 2)];
  }
    
  return answer;
}
cs