코딩테스트/프로그래머스

프로그래머스 1LV C++ 가운데 글자 가져오기 풀이

sky하연 2024. 3. 15. 14:29

문제 설명

단어 s의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다.

재한사항
  • s는 길이가 1 이상, 100이하인 스트링입니다.

각 부분별 코드 설명

문자열 s의 길이를 가져 온 다음 중간값을 구하기 위해 2로 나눈다.

int strl = s.length();
    int center_num;
    string answer;
    
    center_num = strl/2;

 

s의 길이가 짝수 일경우 완벽한 중간이 없으므로 중앙의 두 글자를 출력해야한다.

중앙의 두글자는 중간값과 중간값+1의 자리에 있는 것 이지만 배열은 0부터 시작하기 때문에

중간 값-1, 중간 값으로 중앙 두글자를 구할 수 있다.

 

홀수 일 경우는 나눠질 때 X.5 으로 나누어져 반내림되기 때문에 굳이 1을 빼줄 필요 없이

그냥 중간 값을 가지고도 구할 수 있다.

 

짝수는 두글자를 더해주고 리턴해줘야 하는데 +가 안되서 String의 다른 함수를 사용하였다.

str1.pushback(str2)은 str1의 맨뒤에 str2값을 추가해주는 함수이다.

if(s.length() % 2 == 0){//짝수
        cout<<s[center_num-1]<<s[center_num];
        answer.push_back(s[center_num-1]);
        answer.push_back(s[center_num]);
    }else{//홀수
        cout<<s[center_num];
        answer = s[center_num];
    }

  


전체코드

#include <string>
#include <vector>
#include <iostream>

using namespace std;

string solution(string s) {
    
    int strl = s.length();
    int center_num;
    string answer;
    
    center_num = strl/2;
    
    if(s.length() % 2 == 0){//짝수
        cout<<s[center_num-1]<<s[center_num];
        answer.push_back(s[center_num-1]);
        answer.push_back(s[center_num]);
    }else{//홀수
        cout<<s[center_num];
        answer = s[center_num];
    }
    
    return answer;
}