codewars - Get the Middle Character(7 kyu)(java)

codewars - Get the Middle Character(7 kyu)(java)

728x90

codewars 사이트를 알게된 뒤로 영어공부할 때 간간히 들어가는 문제 사이트인데, 일단은 영어에 대한 이해부터 높이기 위해 낮은 난이도부터 천천히 풀어보고 있습니다. codewars의 난이도는 확실히 다른 한국 문제 사이트보다 규격화가 덜 된 느낌이라 같은 난이도인데도 문제가 천차만별인 것 같습니다.

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"

#Input

A word (string) of length 0 < str < 1000 (In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases). You do not need to test for this. This is only here to tell you that you do not need to worry about your solution timing out.

#Output

The middle character(s) of the word represented as a string.

문제는 이렇습니다. 먼저 단어가 하나 주어집니다. 이 단어의 중간 문자를 하나 표시해야 하는데, 짝수인 경우에는 2개의 문자를, 홀수인 경우에는 1개의 문자를 표시하는 문제입니다.

인풋 조건은 단어의 길이는 0보다 크고 1000보다 작으며 시간초과에 대해서 신경쓰지 않아도 된답니다.

출력의 경우 String 형식으로 출력해야 한다고 알려주고 있습니다.

class Kata { public static String getMiddle(String word) { char[] string = word.toCharArray(); StringBuilder result = new StringBuilder(); if(string.length %2 == 0) { //짝수 result.append(string[string.length/2-1]); result.append(string[string.length/2]); } else { //홀수 result.append(string[string.length/2]); } return result.toString(); } }

위는 제가 제출한 해답입니다. 코딩 테스트를 자주 하면서 저는 습관적으로 StringBuilder를 쓰는 경향이 있기도 하고, 좀 더 편하게 보기 위해 이런식으로 작성하게 되었습니다. 코드 내부 내용은 크게 어려운 부분이 없다고 생각해서 따로 설명은 생략하겠습니다.

class Kata { public static String getMiddle(String word) { int length = word.length(); return (length % 2 != 0) ? String.valueOf(word.charAt(length / 2)) : word.substring(length / 2 - 1, length / 2 + 1); } }

위 코드는 best solution 중 하나인데, 이 글을 보고 제가 얼마나 코드를 길게 작성했는지 깨닫게 되었습니다.

코드워스를 보다보면 신박하게 짧게, 그러나 왜 떠올리지 못했지? 하는 간단하게 작성된 코드가 굉장히 많다는 것을 깨닫게 됩니다. 확실히 코드를 더 깔끔하고 간단하게 작성하기 위해서 한 번 더 생각해야 한다는 것을 깨닫게 해주는 부분이라 유용한 사이트라고 생각하고 있습니다.

728x90

from http://no-dev-nk.tistory.com/57 by ccl(A) rewrite - 2021-11-02 12:01:20