프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

📄 문제

덧셈, 뺄셈 수식들이 'X [연산자] Y = Z' 형태로 들어있는 문자열 배열 quiz가 매개변수로 주어집니다. 수식이 옳다면 "O"를 틀리다면 "X"를 순서대로 담은 배열을 return하도록 solution 함수를 완성해주세요.

 

📝 풀이

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

using namespace std;

vector<string> split(string input, char delimiter)
{
    vector<string> result; // 결과를 리턴할 string 벡터
    stringstream ss(input); // sstream
    string token; // split된 문자열을 임시로 담을 토큰
    
    // getline 함수로 받아온 후 벡터에 삽입
    while(getline(ss, token, delimiter))
        result.push_back(token);
    
    return result;
};

vector<string> solution(vector<string> quiz) {
    
    vector<string> answer;

    for(string str : quiz)
    {
        vector<string> splited = split(str, ' ');
        
        if(splited[1] == "+")
            answer.push_back(stoi(splited[0]) + stoi(splited[2]) == stoi(splited[4]) ? "O" : "X");
        else
            answer.push_back(stoi(splited[0]) - stoi(splited[2]) == stoi(splited[4]) ? "O" : "X");
    }
    
    return answer;
}
  • 문자열을 스플릿 한 후 규칙에 맞게 계산을 수행합니다.
bonnate