信息學奧賽一本通1331【例1-2】後綴表達式的值 (棧)

1331:【例1-2】後綴表達式的值


時間限制: 10 ms         內存限制: 65536 KB
提交數: 21345     通過數: 3892

【題目描述】

從鍵盤讀入一個後綴表達式(字符串),只含有0-9組成的運算數及加(+)、減(—)、乘(*)、除(/)四種運算符。每個運算數之間用一個空格隔開,不需要判斷給你的表達式是否合法。以@作爲結束標誌。

比如,16–9*(4+3)轉換成後綴表達式爲:16□9□4□3□+*–,在字符數組A中的形式爲:

棧中的變化情況:

運行結果:-47

提示:輸入字符串長度小於250,參與運算的整數及結果之絕對值均在2的64次方範圍內,如有除法保證能整除。

【輸入】

一個後綴表達式。

【輸出】

一個後綴表達式的值。

【輸入樣例】

16 9 4 3 +*-@

【輸出樣例】

-47


遇到數字就保存到num數組中(可能是多位數,需進行處理),注意數據範圍,num數組需用longlong,否則過不了。

遇到字符就讓最後保存的兩個數進行運算,注意減法和除法的運算順序,倒數第二個保存的數減去(除以)最後保存的那個數,運算後將結果保存在倒數第二個保存的數的位置(此時這個數更新爲最後保存的數的位置,其數組下標前一個位置則爲此時的倒數第二個保存的數),以此類推,這是用數組模擬棧的方法。

#include <iostream>
#include <string>
#include <stack>
#include <cstring> 
using namespace std;

long long num[1005];

int main()
{
	string str;
	getline(cin, str);
	int len = str.length();
	int cnt = 0;
	for (int i = 0; i < len - 1; i ++) { // i<len-1爲了不包含最後的@
		if (str[i] == '+') { // 對四則運算進行處理 注意減法和除法的 被減數 和 被除數 的位置
			num[cnt-2] += num[cnt-1];
			cnt --;
		}
		else if (str[i] == '-') {
			num[cnt-2] -= num[cnt-1];
			cnt --;
		}
		else if (str[i] == '*') {
			num[cnt-2] *= num[cnt-1];
			cnt --;
		}
		else if (str[i] == '/') {
			num[cnt-2] /= num[cnt-1];
			cnt --;
		}
		else {
			long long x = 0;
			while (str[i] != ' ') {
				x = x*10 + str[i]-'0';
				i ++;
			}
			num[cnt++] = x;//printf("%lld\n", x); //測試num中保存的數值
		}
	}
	cout << num[0] << endl;
	return 0;
}

補充一個用stack的

#include <iostream>
#include <string>
#include <cstdio>
#include <stack>
#include <cstring> 
using namespace std;

stack <long long> s;

int main()
{
	string str;
	getline(cin, str);
	int len = str.length();
	long long x;
	for (int i = 0; i < len - 1; i ++) { 
		x = 0;
		long long a, b;
		if (str[i] == '+') { 
			a = s.top();
			s.pop();
			b = s.top();
			s.pop();
			s.push(a+b);
		}
		else if (str[i] == '-') {
			a = s.top();
			s.pop();
			b = s.top();
			s.pop();
			s.push(b-a);
		}
		else if (str[i] == '*') {
			a = s.top();
			s.pop();
			b = s.top();
			s.pop();
			s.push(a*b);
		}
		else if (str[i] == '/') {
			a = s.top();
			s.pop();
			b = s.top();
			s.pop();
			s.push(b/a);
		}
		while (str[i] >= '0' && str[i] <= '9') {
			x = x*10 + str[i]-'0';
			if (str[i+1] == ' ') {
				s.push(x);
				x = 0;
			}
			i ++;
		}
	}
	printf("%lld\n", s.top());
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章