华为机试:24点游戏算法

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

double cacul(double a, double b, char op) {
    switch(op) {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/': return a / b;
    }
    return 0;
}

int main() {
    double num;
    vector<double> nums;
    while (cin >> num) {
        nums.push_back(num);
    }
    sort(nums.begin(), nums.end());
    string oper = "+-*/";
    do {
        for (char op1 : oper) {
            for (char op2 : oper) {
                for (char op3 : oper) {
                    double first = cacul(nums[0], nums[1], op1);
                    double second = cacul(first, nums[2], op2);
                    double third = cacul(second, nums[3], op3);
                    if (third == 24) {
                        cout << "true" << endl;
                        return 0;
                    }
                }
            }
        }
    }while (next_permutation(nums.begin(), nums.end()));
    cout << "false" << endl;
    return 0;
}

全部评论
多谢佬的分享
点赞 回复 分享
发布于 2023-03-10 11:27 天津
今日学习进度+1
点赞 回复 分享
发布于 2023-03-10 11:42 黑龙江

相关推荐

数开小菜鸡:你是我今早见过的最美的牛客女孩......
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务