
【题目网站】
信息学奥赛一本通(C++版)在线评测系统
【题目考点】
栈的使用
【题目思路】
- 使用栈存入所有数字(注意:最大范围为2的64次方,所以应用long long)
- 用一个char类型的数组存入符号
- 每取出两个数字后再用符号 *** 作并把结果存入栈(注意:减法时是第二个数字减第一个数字)
- 循环 *** 作第三步直至结束
- 输出答案
【题目答案】
#include
#include
#include
using namespace std;
stack s;
string str;
char sym[255];
long long num, sym_len;
int main(){
getline(cin, str);
for (long long i = 0; i < str.size(); i++){
if (str[i] >= '0' && str[i] <= '9'){//判断是否为数字
num = num * 10 + str[i] - '0';
}else if (str[i] == ' '){//此处处理多位数的存放
s.push(num);
num = 0;
}else if (str[i] != '@'){//存储符号
sym_len++;
sym[sym_len] = str[i];
}
}
for (long long i = 1; i <= sym_len; i++){
long long first, second;
if (sym[i] == '+'){//判断符号是否为加号
first = s.top();
s.pop();
second = s.top() + first;
s.pop();
s.push(second);
}else if (sym[i] == '-'){//判断符号是否为减号
first = s.top();
s.pop();
second = s.top() - first;
s.pop();
s.push(second);
}else if (sym[i] == '*'){//判断符号是否为乘号
first = s.top();
s.pop();
second = s.top() * first;
s.pop();
s.push(second);
}else{//符号为除号
first = s.top();
s.pop();
second = s.top() / first;
s.pop();
s.push(second);
}
}
cout << s.top() << endl;
return 0;
}
【常见错误】
- 第12行未使用getline而使用cin
- 第16-18行为处理多位数
- 第35、47行为第二个数减、除以第一个数
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)