Algorithm/C++ - 프로그래머스

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

ㅇㅇ잉 2021. 2. 8. 22:13

간단하게 풀 수 있었다.

index가 0에서부터 시작하는거 주의

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <string>
#include <vector>
 
using namespace std;
 
string solution(string s) {
    string answer = "";
    
    if(s.length()%2==0){
        answer.push_back(s[s.length()/2-1]);
        answer.push_back(s[s.length()/2]);
    }else{
        answer.push_back(s[s.length()/2]);
    }
    
    return answer;
}
cs

 

이건 다른 풀이다.

굉장히,,,깔끔하게 풀 수 있구나,,

1
2
3
4
5
6
7
#include <string>
 
using namespace std;
 
string solution(string s) {
    return s.length()&1 ? s.substr(s.length()*0.5,1) : s.substr(s.length()*0.5-1,2);
}
cs