Title: Define that each game consists of four numbers from 1 to 9 and three four operators, ensuring that the four operators separate the numbers from each other, without parentheses and other characters, and that the operators are performed in the order of four operations. Addition is represented by symbol + subtraction by symbol-representation, multiplication by lowercase letter x and division by symbol/representation. Dividing is dividing in the game.
Now give the solution of n games, please write a program to verify whether the result of each game is 24.
Input: The first line input an integer n, from line 2 to line n+1, each line contains a string of 7 length, for the above 24-point game, to ensure that the data format is legitimate.
Output: Contains n rows. For each game, if the result is 24, the output string Yes, or the output string No
Example:
Input:
10
9+3+4x3
5+4x5x5
7-9-9+8
5x6/5x4
3+5+7+9
1x1+9-9
1x9-5/9
8/5+6x9
6x7-3x6
6x4+4/5
Output:
Yes
No
No
Yes
Yes
No
No
No
Yes
Yes
Analysis: Errors are usually not clearly seen. The multiplication is a lowercase letter x. Divisions are divisions.
#include<iostream> using namespace std; bool high_cal(char ch) { if(ch=='x'||ch=='/')return true; return false; } int cal(char ch, int x, int y) { switch(ch) { case '+':return x+y; case '-':return x-y; case 'x':return x*y; case '/':return x/y; default:return 0; } } int main() { int n; char str[10]; cin>>n; for(int i = 0; i < n; i++) { cin>>str; int num = 0; int num1 = str[0]-'0'; int num2 = str[2]-'0'; int num3 = str[4]-'0'; int num4 = str[6]-'0'; char ch1 = str[1]; char ch2 = str[3]; char ch3 = str[5]; if(high_cal(ch2)){ if(high_cal(ch1)){ if(high_cal(ch3)) num = cal(ch3, cal(ch2, cal(ch1, num1, num2), num3), num4); else num = cal(ch3, cal(ch2, cal(ch1, num1, num2), num3), num4); }else{ if(high_cal(ch3)) num = cal(ch1, num1, cal(ch3, cal(ch2, num2, num3), num4)); else num = cal(ch3, cal(ch1, num1, cal(ch2, num2, num3)), num4); } }else{ if(high_cal(ch1)){ if(high_cal(ch3)) num = cal(ch2, cal(ch1, num1, num2), cal(ch3, num3, num4)); else num = cal(ch3, cal(ch2, cal(ch1, num1, num2),num3),num4); }else{ if(high_cal(ch3)) num = cal(ch2, cal(ch1, num1, num2), cal(ch3, num3, num4)); else num = cal(ch3, cal(ch2, cal(ch1, num1, num2),num3),num4); } } if(num == 24)cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }