πŸ“Œ 1. 문제


[Codewars, 7kyu] Get the Middle Character


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.


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) {
  const str = s.split("");
  const count = str.length;
  if (count % 2) {
    return str[Math.floor(count / 2)];
  } else {
    return str[count / 2 - 1] + str[count / 2];
  }
}

πŸ‘ Best

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


  • κ°€μš΄λ° λ¬Έμžμ—΄ μ°ΎκΈ° 문제둜, bestν’€μ΄μ—μ„œ μ‚¬μš©ν•œ substr() λ©”μ„œλ“œλŠ” λ¬Έμžμ—΄μ—μ„œ νŠΉμ • μœ„μΉ˜μ—μ„œ μ‹œμž‘ν•˜μ—¬ νŠΉμ • 문자 수 만큼의 λ¬Έμžλ“€μ„ λ°˜ν™˜ν•˜λŠ” λ©”μ„œλ“œλ‹€. 그런데 MDNλ¬Έμ„œμ—μ„œ ν•΄λ‹Ή λ©”μ„œλ“œλŠ” μ‚¬μš©ν•˜μ§€ 말 것을 ꢌμž₯ν•˜λŠ” 뢀둝이 μžˆμ–΄μ„œ substr()λŠ” μ•ˆμ“°λŠ” 걸루.. μ‚Όν•­μ—°μ‚°μžλŠ” μ‚¬μš©ν•΄μ„œ μ½”λ“œ κ°„κ²°ν•˜κ²Œ λ§Œλ“€κΈ°