자바스크립트 알고리즘 문제풀이 가운데 문자 출력

버건디·2023년 1월 20일
0

소문자로 된 단어(문자열)가 입력되면 그 단어의 가운데 문자를 출력하는 프로그램을 작성하세 요. 단 단어의 길이가 짝수일 경우 가운데 2개의 문자를 출력합니다.
▣ 입력설명
첫 줄에 문자열이 입력된다. 문자열의 길이는 100을 넘지 않습니다.
▣ 출력설명
첫 줄에 가운데 문자를 출력합니다.
▣ 입력예제 1
study
▣ 출력예제 1
u
▣ 입력예제 2
good
▣ 출력예제 2
oo

내 풀이

const input = `study`;

function solution(input) {
  let answer = "";

  if (input.length % 2 !== 0) {
    let index = Math.floor(input.length / 2);
    answer = input[index];
  } else if (input.length % 2 === 0) {
    let index = input.length / 2;
    answer = input[index - 1] + input[index];
  }

  return answer;
}

답 풀이

const input = `good`;

function solution(input) {
  let answer;
  let mid = Math.floor(input.length / 2);
  if (input.length % 2 === 1) {
    answer = input.substring(mid, mid + 1);
  } else {
    answer = input.substring(mid - 1, mid + 1);
  }

  return answer;
}
profile
https://brgndy.me/ 로 옮기는 중입니다 :)

0개의 댓글