728x90
프로그래머스 1단계
가운데 글자 가져오기
https://programmers.co.kr/learn/challenges
문제 설명
풀이
class Solution {
public String solution(String s) {
int num = s.length();
String answer = "";
if (num%2==0) {
answer += s.charAt(num/2-1);
answer += s.charAt(num/2);
} else {
answer += s.charAt(num/2);
}
return answer;
}
}
코드 설명
1. 문자열의 길이가 짝수라면 문자열의 가운데 두 글자를 answer에 더한다.
2. 문자열의 길이가 홀수라면 문자열의 가운데 글자를 answer에 더한다.
메소드 설명
메소드 | 설명 |
.charAt() | 원하는 위치에 있는 문자를 char 타입으로 가져오는 메소드 |
728x90
'알고리즘 > 프로그래머스 1단계' 카테고리의 다른 글
[프로그래머스] 수박수박수박수박수박수? (0) | 2022.04.23 |
---|---|
[프로그래머스] 서울에서 김서방 찾기 (0) | 2022.04.23 |
[프로그래머스] 약수의 합 (0) | 2022.04.23 |
[프로그래머스] 문자열을 정수로 바꾸기 (1) | 2022.04.23 |
[프로그래머스] 소수 찾기 (0) | 2022.04.23 |
댓글