题解 | #24点运算#
24点运算
https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
#include <iostream> #include <sstream> #include <string> #include <vector> #include<algorithm> using namespace std; int convert(string a) { if (a == "A") { return 1; } else if (a == "J") { return 11; } else if (a == "Q") { return 12; } else if (a == "K") { return 13; } else if (a == "joker" || a == "JOKER") { return -1; } else { return (a[0] - '0'); } } char convert_to_input(double a) { if (a == 1) { return 'A'; } else if (a == 11) { return 'J'; } else if (a == 12) { return 'Q'; } else if (a == 13) { return 'K'; } else { return (a + '0'); } } double cal(double a, double b, char c) { //根据运算符运算结果 switch (c) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } return 0; } bool check(vector<double>& nums) { char op[4] = { '+', '-', '*', '/' }; sort(nums.begin(), nums.end()); //先按照从小到大排 do { for (int i = 0; i < 4; i++) { //遍历三个位置的所有可能运算符 for (int j = 0; j < 4; j++) { for (int k = 0; k < 4; k++) { double first = cal(nums[0], nums[1], op[i]); //依次运算 double second = cal(first, nums[2], op[j]); double third = cal(second, nums[3], op[k]); if (third == 24) //判断是否等于24 { cout << convert_to_input(nums[0]) << op[i] << convert_to_input(nums[1]) << op[j] << convert_to_input(nums[2]) << op[k] << convert_to_input(nums[3]) << endl; return true; } } } } } while (next_permutation(nums.begin(), nums.end())); //依次找到其他排列 return false; } int main() { string strs; getline(cin ,strs); stringstream input(strs); string s; vector<double> NUM; while(input >> s) { NUM.push_back(convert(s)); } if (find(NUM.begin(),NUM.end(),-1.0) != NUM.end()) { cout << "ERROR"; } else if (!check(NUM)) { cout << "NONE"; } } // 64 位输出请用 printf("%lld")