1. 程式人生 > >資料結構與演算法題目集7-21——求字首表示式的值

資料結構與演算法題目集7-21——求字首表示式的值

我的資料結構與演算法題目集程式碼倉:https://github.com/617076674/Data-structure-and-algorithm-topic-set

原題連結:https://pintia.cn/problem-sets/15/problems/836

題目描述:

知識點:字首表示式的計算

思路:利用棧計算字首表示式的值

字首表示式的計算規則:

從右往左遍歷表示式的每個數字和符號,遇到是數字就進棧, 遇到是符號,就將處於棧頂兩個數字出棧,進行運算,運算結果進棧,一直到最終獲得結果。

注意:本題所給的數字可能自帶符號,即可能出現"-1"、"+2"這樣的數字,還可能出現小數點

C++程式碼:

#include<iostream>
#include<stack>
#include<cstring>

using namespace std;

int main() {
	char input[31];
	scanf("%[^\n]", input);
	stack<double> Stack;
	for(int i = strlen(input) - 1; i >= 0; i--) {
		char c = input[i];
		if((c >= '0' && c <= '9') || (c == '.')) {
			char temp[31];
			int j = i, index = 0;
			while(j >= 0 && ((input[j] >= '0' && input[j] <= '9') || input[j] == '.')) {
				temp[index++] = input[j];
				j--;
			}
			temp[index] = '\0';
			char rev[31];
			for(int k = 0; k < strlen(temp); k++) {
				rev[k] = temp[index - k - 1];
			}
			rev[index] = '\0';
			double num;
			sscanf(rev, "%lf", &num);
			if(input[j] == '-') {
				num = -num;
				i = j;
			} else if(input[j] == '+') {
				i = j;
			}else{
				i = j + 1;
			}
			Stack.push(num);
		} else if(c != ' ') {
			double num1 = Stack.top();
			Stack.pop();
			double num2 = Stack.top();
			Stack.pop();
			if(c == '+') {
				Stack.push(num1 + num2);
			} else if(c == '-') {
				Stack.push(num1 - num2);
			} else if(c == '*') {
				Stack.push(num1 * num2);
			} else if(c == '/') {
				if(num2 == 0){
					printf("ERROR\n");
					return 0;
				}
				Stack.push(num1 / num2);
			}
		}
	}
	if(Stack.empty()) {
		printf("ERROR\n");
		return 0;
	}
	printf("%.1f\n", Stack.top());
	return 0;
}

C++解題報告: