24运算点问题

    技术2022-07-12  69

    牛客网华为机考:24运算点问题:

    看到一个逻辑很清楚的题解: 计算24点是一种扑克牌益智游戏,随机抽出4张扑克牌,通过加(+),减(-),乘(*), 除(/)四种运算法则计算得到整数24,本问题中,扑克牌通过如下字符或者字符串表示,其中,小写joker表示小王,大写JOKER表示大王:

    3 4 5 6 7 8 9 10 J Q K A 2 joker JOKER

    本程序要求实现:输入4张牌,输出一个算式,算式的结果为24点。

    详细说明:

    1.运算只考虑加减乘除运算,没有阶乘等特殊运算符号,友情提醒,整数除法要当心; 2.牌面210对应的权值为210, J、Q、K、A权值分别为为11、12、13、1; 3.输入4张牌为字符串形式,以一个空格隔开,首尾无空格;如果输入的4张牌中包含大小王,则输出字符串“ERROR”,表示无法运算; 4.输出的算式格式为4张牌通过±/四个运算符相连,中间无空格,4张牌出现顺序任意,只要结果正确; 5.输出算式的运算顺序从左至右,不包含括号,如1+2+34的结果为24 6.如果存在多种算式都能计算得出24,只需输出一种即可,如果无法得出24,则输出“NONE”表示无解。

    链接:https://www.nowcoder.com/questionTerminal/7e124483271e4c979a82eb2956544f9d?f=discussion 来源:牛客网 bool get(int a, int b, char& ops){ if(a+b == 24) {ops = '+';return true;} if(a-b == 24) {ops = '-';return true;} if(a*b == 24) {ops = '*';return true;} if(a != 0 && b%a == 0 && b/a == 24) {ops = '/';return true;} return false; } bool get(int a, int b, int c, char& ops1, char& ops2){ if(get(a+b, c, ops2)) {ops1 = '+';return true;} if(get(a-b, c, ops2)) {ops1 = '-';return true;} if(get(a*b, c, ops2)) {ops1 = '*';return true;} if(b != 0 && a%b == 0 && get(a/b, c, ops2)) {ops1 = '/';return true;} return false; } bool get(int a, int b, int c, int d, char& ops1, char& ops2, char& ops3){ if(get(a+b, c, d, ops2, ops3)) {ops1 = '+';return true;} if(get(a-b, c, d, ops2, ops3)) {ops1 = '-';return true;} if(get(a*b, c, d, ops2, ops3)) {ops1 = '*';return true;} if(b != 0 && a%b == 0 && get(a/b, c, d, ops2, ops3)) {ops1 = '/';return true;} return false; }
    Processed: 0.009, SQL: 9