This question is arithmetic, we use the stack to solve it
Use template class stack c ++ in
#include <Stack> // header Stack < int > NUM; // define a stack type int num.push (); // in the stack into a stack element num.pop (); // delete the stack elements on num.top (); // returns the element of the stack, and does not remove num.empty (); // return stack is empty num.size (); // returns the current number of elements in the stack
1. When a character is a digit, num into the stack
2. When the character is "+", the sign is stored in the stack
3. When the character is "-" when, because of a reduced number equal to the opposite of a number of add, so that the next character is stored negated num stack, stack stores Sign "+"
4. When the character is "X", the current character to take the next character q and p, the q * p deposit num
5. When the character is "/", the current character to take the next character q and p, the q / P stores num
Code:
#include<cstdio> #include<cstring> #include<stack> using namespace std; int n; char str[10]; stack<int> num; stack<char> sign; int main() { scanf("%d",&n); getchar(); while(!num.empty()) num.pop(); while(!sign.empty()) sign.pop(); for(int i=0;i<n;i++) { gets(str); int j=0; while(j<strlen(str)) { if(str[j]>'0'&&str[j]<='9') { num.push(str[j]-'0'); } else if(str[j]=='+') { sign.push('+'); } else if(str[j]=='-') { j++; num.push((-1)*(str[j]-'0')); sign.push('+'); } else if(str[j]=='x') { int q=num.top(); num.pop(); j++; int p=str[j]-'0'; num.push(q*p); } else if(str[j]=='/') { int q=num.top(); num.pop(); j++; int p=str[j]-'0'; num.push(q/p); } j++; } while(!sign.empty()) { int q=num.top(); num.pop(); int p=num.top(); num.pop(); sign.pop(); num.push(q+p); } //printf("%d\n",num.top()); if(num.top()==24) printf("Yes\n"); else printf("No\n"); } return 0; }