【一本通】1131:后缀表达式的值

【题目描述】

  从键盘读入一个后缀表达式(字符串),只含有0-9组成的运算数及加(+)、减(—)、乘(*)、除(/)四种运算符。每个运算数之间用一个空格隔开,不需要判断给你的表达式是否合法。以@作为结束标志。
  比如,16–9*(4+3)转换成后缀表达式为:16□9□4□3□+*–,在字符数组A中的形式为:

image

  栈中的变化情况:

image

  运行结果:-47

  提示:输入字符串长度小于250,参与运算的整数及结果之绝对值均在2^64范围内,如有除法保证能整除。

【输入】

  一个后缀表达式。

【输出】

  一个后缀表达式的值。

【输入样例】

16 9 4 3 +*-@

【输出样例】

-47

【代码】

代码未通过,请各位巨佬指正(bu

#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main() {
	string list;
	getline(cin, list);
	stack<int> s;
	for (int i=0; i<list.length(); i++) {
		if (list[i]>='0' && list[i]<='9') {
			int sum = 0;
			while (list[i] != ' ') {
				sum = sum*10;
				sum += list[i]-'0';	
				i++;
			}
			s.push(sum);
		} else if (list[i] != '@') {
			int a = s.top();
			s.pop();
			int b = s.top();
			s.pop();
			if (list[i] == '+') {
				s.push(b+a);
			} else if (list[i] == '-') {
				s.push(b-a);
			} else if (list[i] == '*') {
				s.push(b*a);
			} else if (list[i] == '/') {
				s.push(b/a);
			}
		}
	}
	cout << s.top();
	return 0;
}
posted @ 2023-02-07 21:25  SquareBot164  阅读(180)  评论(0)    收藏  举报