(codeWars) Get the Middle Character

호두파파·2021년 2월 26일
0

알고리즘 연습

목록 보기
6/60
post-thumbnail

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"

문제 풀이

배열을 이용해 문제를 해결하려는 습관을 타파해야겠다는 생각이 많이 들었던 문제,
앞선 문제에서 charAt()을 활용해, 문자열에서 n번째 문자를 뽑아내는 메소드를 학습했음에도, splice나 slice같은 메소드를 사용하려고 했던 것이 화근이었다.

물론, slice를 활용해서도 문제를 해결할 수 있지만, charAt()을 활용해 문제를 해결하는 방법이 조금 더 명쾌했다.

// 가운데 문자를 리턴하는 문제 

function solution(s) {
  const len = s.length;
  const middle = len / 2;
  for (let x of s) {
    if ( len % 2 === 0) {
      return s.charAt(middle - 1) + s.charAt(middle);
    } else {
      return s.charAt(Math.floor(middle));
    }
  }
}

const s = 'test';
const n = 'testing';
const x = 'abcdefg';

console.log(solution(s));
console.log(solution(n));
console.log(solution(x));


다른 문제 풀이

function getMiddle(s) {
  return s.slice((s.length-1)/2, s.length/2+1);
}

다시 한 번 자바 스크립트의 유연성에 박수를 ..

profile
안녕하세요 주니어 프론트엔드 개발자 양윤성입니다.

0개의 댓글