這道題是四則運算,我們用棧來解決它
使用c++中的模板類stack
#include<stack> //頭文件 stack <int> num; //定義一個int型棧 num.push(); //在棧頂上堆進一個元素 num.pop(); //刪除掉棧頂上的元素 num.top(); //返回棧頂的元素,並不會刪除 num.empty(); //返回棧是否為空 num.size(); //返回當前棧中元素的個數
1.當字符為數字時,存入num棧中
2.當字符是“+”時,存入sign棧中
3.當字符是“-”時,因為減一個數等於加一個數的相反數,所以將下一個字符取反存入num棧,sign棧存入“+”
4.當字符是“X”時,取當前字符q和下一個字符p,將q*p存入num
5.當字符是“/”時,取當前字符q和下一個字符p,將q/p存入num
代碼:
#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; }