Programmers[level 2] 수식최대화

지현·2021년 7월 27일
0

Programmers

목록 보기
4/5

수식최대화

  • 문제 설명

  • 제한 사항

  • 입출력 에

  • 입출력 예에 대한 설명

코드

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

long long calc(long long a,long long b, char op){
    if (op == '-')  return a-b;
    else if (op == '+')  return a+b;
    else    return a*b;
}

long long solution(string expression){
    long long answer = 0;
    long long _max =0;
    vector <char> oper_list =  { '*', '+', '-' };
    vector <long long> number;
    vector <char> oper;
    string num = "";

    for(int i=0; i<expression.size(); i++){
        if (expression[i]=='+' || expression[i]=='*' || expression[i]=='-'){
            oper.push_back(expression[i]);
            number.push_back(atoi(num.c_str())); // c_str : string to char, atoi: char to int
            num="";
        }
        else {
            num += expression[i];  
        }
    }
    number.push_back(atoi(num.c_str())); // 마지막 숫자까지 push 
    
    do{
        vector <char> tmp_oper = oper;
        vector <long long> tmp_num = number;
        for (int i=0; i<3; i++){
            for (int j=0; j<tmp_oper.size(); j++){
                if (tmp_oper[j] == oper_list[i]){ //  oper_list= { '*', '+', '-' };
                    tmp_num[j] = calc(tmp_num[j],tmp_num[j+1],oper_list[i]);
                    tmp_num.erase(tmp_num.begin()+j+1);
                    tmp_oper.erase(tmp_oper.begin()+j);
                    j--;
                }
            }
        } 
        if(_max < abs(tmp_num[0])){
            _max = abs(tmp_num[0]);
        }
    } while(next_permutation(oper_list.begin(),oper_list.end()));
    answer = _max;
    return answer;
}


  • 배운 것
  1. c_str : string to char / atoi: char to int
    -> stoi : string to int

  2. next_permutation 사용

0개의 댓글

관련 채용 정보