blog.itcode.devblog.itcode.dev

[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.

[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.
RWB0104
@RWBwritten at 2021-12-16 10:18:27
Programmers

시리즈 모아보기

Programmers

33 / 78
RankLanguage 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
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08