(알고리즘) CodeWars : Get the Middle Character

호두파파·2021년 5월 12일
0

알고리즘 연습

목록 보기
13/60


Description:

You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.

Examples:

  • Kata.getMiddle("test") should return "es"
  • Kata.getMiddle("testing") should return "t"
  • Kata.getMiddle("middle") should return "dd"
  • Kata.getMiddle("A") should return "A"

내 문제 풀이

function getMiddle(s) {
  let middle = Math.floor(s.length/2);
  return s.length % 2 === 0
        ? s.slice(middle-1, middle+1)
        : s.slice(middle, middle+1);
}

다른 문제풀이

function getMiddle(s) {
  return s.substr(Math.ceil(s.length / 2 - 1), s.length % 2 === 0 ? 2 : 1);
}
profile
안녕하세요 주니어 프론트엔드 개발자 양윤성입니다.

0개의 댓글