기본 콘텐츠로 건너뛰기

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

public class StringExercise{
    String getMiddle(String word){
        int len = word.length();
        if(len%2==0) {//짝수
            return word.substring(len/2-1, len/2+1);
        }
        else {//홀수
            return word.substring(len/2, len/2+1);          
        }    
    }
    // 아래는 테스트로 출력해 보기 위한 코드입니다.
    public static void  main(String[] args){
        StringExercise se = new StringExercise();
        System.out.println(se.getMiddle("power"));
    }
}

아래와 같은 풀이도 있다. 짝수와 홀수를 2로 나눴을때의 결과를 잘 활용한 것같다. 배워야지
class StringExercise{
    String getMiddle(String word){

        return word.substring((word.length()-1)/2, word.length()/2 + 1);    
    }
    // 아래는 테스트로 출력해 보기 위한 코드입니다.
    public static void  main(String[] args){
        StringExercise se = new StringExercise();
        System.out.println(se.getMiddle("power"));
    }
}

댓글

이 블로그의 인기 게시물

프로그래머스 - 시저 암호

public class Caesar { String caesar ( String s , int n ) { n %= 26 ; String result = "" ; char [] temp = s . toCharArray (); for ( int i = 0 ; i < temp . length ; i ++) { if ( temp [ i ]>= 'a' && temp [ i ]<= 'z' ) temp [ i ] = ( char ) (( temp [ i ]+ n )> 'z' ? ( temp [ i ]+ n - 1 )% 'z' + 'a' : ( temp [ i ]+ n )); else if ( temp [ i ]>= 'A' && temp [ i ]<= 'Z' ) temp [ i ] = ( char ) (( temp [ i ]+ n )> 'Z' ? ( temp [ i ]+ n - 1 )% 'Z' + 'A' : ( temp [ i ]+ n )); result += temp [ i ]; } return result ; } public static void main ( String [] args ) { Caesar c = new Caesar (); System . out . println ( "s는 'a B z', n은 4인 경우: " + c . caesar ( ...