본문 바로가기
알고리즘/프로그래머스 1단계

[프로그래머스] 가운데 글자 가져오기

by lanuarius19 2022. 4. 23.
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

댓글