프로그래밍/코테 기반 지식

[코테 준비] 문제별 알아야 할 개념과 함수

jinkwon.kim 2022. 6. 27. 22:35
728x90
반응형

홀짝

1. 문제 푸는 원리

    숫자를 2로 나눈 몫이 0이면 짝수임을 응용, 단 0은 예외 처리가 필요함.

#include <string>
#include <vector>

using namespace std;

string solution(int num) {
    string answer = "";
    if (num == 0)
        answer = "Even";
    else if (num % 2 == 0) {
        answer = "Even";
    } else {
        answer = "Odd";
    }
    return answer;
}

문자열 재배치 문제 

1. 문제 푸는 원리

    string -> vector로 변환 -> vector sorting -> 합치기

2. 사용된 코드

    1) std::vector

        (1) 헤더

            #include <vector>

        (2) 함수

            push_back()

    2) sort

        (1) 헤더

            #include <algorithm>

        (2) 함수 

            - 오름 차순 정렬

                sort(v.begin(), v.end())

            - 내림 차순 정렬

                sort(v.begin(), v.end(), greater<>())

    3) std::ostirngstream

        (1) #include <sstream> 

/#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <algorithm>
#include <sstream>

using namespace std;

string solution(string s) {
    string answer = ""; 
    vector<char> up; 
    vector<char> lower;
    
    for(int i = 0; i < s.length(); i++) {
        if (isupper(s[i])) {
            //std::cout<< "대문자" << s[i] << std::endl;
            up.push_back(s[i]);
            sort(up.begin(), up.end(), greater<>());
        } else {
            //std::cout<< "소문자" << s[i] << std::endl;
            lower.push_back(s[i]);
            sort(lower.begin(), lower.end(), greater<>());
        }
    }   
    
    std::ostringstream oss;
     for (const auto &it : lower) {
        oss << it; 
    }   
    for (const auto &it : up) {
        oss << it; 
    }   

    
    //std::cout << oss.str() << std::endl;
    answer = oss.str();
    return answer;
}

int main ()
{
    solution("aaaaaz");
}
728x90
반응형