[프로그래머스] 코딩테스트 - 가운데 글자 가져오기

김예림·2021년 11월 16일
0

제시된 문제는

function solution(s) {
    if (s.length % 2 === 0) {
        return s.substr(s.length / 2 -1, 2)
    } else {
        return s.substr(s.length / 2 , 1)
    }
}

substr함수를 사용해서 풀어봤다.

Math.ceil 함수를 이용한 다른사람의 풀이

function solution(s) {
    return s.substr(Math.ceil(s.length / 2) - 1, s.length % 2 === 0 ? 2 : 1);
}

Math.ceil 함수는 주어진 숫자보다 크거나 같은 숫자 중 가장 작은 숫자를 integer 로 반환하는 함수이다.

내가 짠 코드보다 훨씬 더 간결하다는 것을 알 수 있다.

profile
초보개발자

0개의 댓글