题解 | #24点运算#

24点运算

https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d

#include <cctype>
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
#include <stack>
using namespace std;

vector<char> symbol = {'+', '-', '*', '/'};
vector<string> pok = {"A","2","3","4","5","6","7","8","9","10","J","Q","K",};

bool calculate(string s) {
    stack<int> st;
    int n = s.size(), loc = 0, sum = 0;
    char sy = '+';
    string tm;
    while (loc <= n) {
        if (loc < n && isdigit(s[loc])) {
            tm += s[loc];
        } else if ((loc == n) || (loc < n && !isdigit(s[loc]))) {
            switch (sy) {
                case '+':
                    sum += stoi(tm);
                    tm.clear();
                    break;
                case '-':
                    sum -= stoi(tm);
                    tm.clear();
                    break;
                case '*':
                    sum *= stoi(tm);
                    tm.clear();
                    break;
                case '/':
                    sum /= stoi(tm);
                    tm.clear();
                    break;
            }
            sy = s[loc];
        }
        ++loc;
    }

    if(sum == 24){
        return true;
    }else {
        return false;
    }
}


bool combination(vector<int> ins) {
    string s;
    sort(ins.begin(), ins.end());
    do {
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                for (int k = 0; k < 4; k++) {
                    s = to_string(ins[0]) + symbol[i] + to_string(ins[1]) + symbol[j] + to_string(ins[2]) + symbol[k] + to_string(ins[3]);
                    if (calculate(s)) {
                        s = pok[ins[0] - 1] + symbol[i] + pok[ins[1] - 1] + symbol[j] + pok[ins[2] - 1] + symbol[k] + pok[ins[3] - 1];
                        cout << s << endl;
                        return true;
                    }
                }
            }
        }
    } while (next_permutation(ins.begin(), ins.end()));
    return false;
}



int main() {
    map<string, int> mp = {{"3", 3}, {"4", 4}, {"5", 5}, {"6", 6}, {"7", 7}, {"8", 8}, {"9", 9}, {"10", 10}, {"J", 11}, {"Q", 12}, {"K", 13}, {"A", 1}, {"2", 2}};
    string s;
    vector<int> ins;
    while (cin >> s) {
        if (mp.find(s) == mp.end()) {
            cout << "ERROR" << endl;
            return 0;
        } else {
            ins.push_back(mp[s]);
        }
    }
    if (!combination(ins)) {
        cout << "NONE" << endl;
        return 0;
    }

    return 0;
}
// 64 位输出请用 printf("%lld")

注意该题目的特殊运算顺序

全部评论

相关推荐

09-01 21:40
已编辑
同济大学 Java
点赞 评论 收藏
分享
08-08 16:33
唐山学院 Java
职场水母:首先,简历太长,对于实习和应届找工作,hr一眼扫的是学历,技术看实习,你写的技术栈字太多了,尽量用一句话概括不用写那么详细,技术面的时候会问的,而且技术栈都会在实习或者项目里体现,你要做的是,把你的简历浓缩为一页,删除没用的东西,比如实践经历,自我评价,这些纯废话,没用,专业技能写的太离谱,你真的熟练掌握了吗,建议都写熟悉,找工作和写论文不一样,追求的是干练和实用,把实习经历和项目提前,把掌握的技术栈写到最后,然后去找实习,
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务