본문 바로가기
알고리즘

가운데 글자 가져오기[연습문제]

by aesup 2021. 2. 26.
728x90
class Solution {
    public String solution(String s) {
        String answer = "";
        if(s.length()%2 == 0){//0,1,2,3
            answer = s.substring(s.length()/2-1, s.length()/2 +1);
            
        }else {//0,1,2,3,4
            int a = Math.round(s.length()/2); 
            answer = s.substring(a, a+1); 
        }
            
            
        
        return answer;
    }
}

고수의 풀이..

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"));
    }
}
728x90

'알고리즘' 카테고리의 다른 글

알고리즘 모임 규칙  (0) 2021.03.05
신입 풀스택 개발자🤦‍♀️👩‍💻  (0) 2021.03.03
java// Stack  (0) 2021.03.03
주식가격  (0) 2021.03.02
두 개 뽑아서 더하기  (0) 2021.02.16