[Programmers / JAVA] Level 1 Getting the Middle Character (12903)
[Programmers / JAVA] Level 1 Getting the Middle Character (12903)
Write a function, solution, that returns the middle character of a word s. If the word's length is even, return the two middle characters.
@RWBwritten at 2021-12-16 10:18:27
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
🔗 Getting the Middle Character
Write a function, solution, that returns the middle character of a word s. If the word's length is even, return the two middle characters.
- s is a string with a length between 1 and 100.
A simple problem: given a string s, return its middle character. However, if the length is even, return two characters.
Determine the length of s to check whether it's odd or even. If it's odd, return one middle character; if even, return two.
JAVA
/** * Getting the Middle Character class * * @author RWB * @since 2021.12.12 Sun 17:43:58 */ class Solution { /** * Method that returns the answer * * @param s: [String] string * * @return [String] answer */ public String solution(String s) { int index = s.length() / 2; return s.length() % 2 == 0 ? s.substring(index - 1, index + 1) : s.substring(index, index + 1); } }
# Programmers# Algorithm# JAVA# Level 1
