From 8e3a6a794d2e18a82df20ca505b9784ce8fd9b20 Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Sun, 26 May 2024 15:44:38 +0800 Subject: [PATCH] =?UTF-8?q?:white=5Fcheck=5Fmark:=20=E4=B8=AD=E7=BC=80?= =?UTF-8?q?=E8=BD=AC=E5=90=8E=E7=BC=80+=E8=A1=A8=E8=BE=BE=E5=BC=8F?= =?UTF-8?q?=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- simple-calculator/main.cc | 76 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 simple-calculator/main.cc diff --git a/simple-calculator/main.cc b/simple-calculator/main.cc new file mode 100644 index 0000000..176bbf4 --- /dev/null +++ b/simple-calculator/main.cc @@ -0,0 +1,76 @@ +#include +#include +#include +#include +using namespace std; + +unordered_map priority{{'(', 0}, {')', 0}, {'+', 1}, {'-', 1}, + {'*', 2}, {'/', 2}, {'^', 3}}; + +string in_order2post_order(string src) { + stack in; + string builder; + for (int i = 0; i < src.size(); i++) { + if (src[i] == ' ') + continue; + if (isdigit(src[i])) + builder += src[i]; + else { + builder += ' '; + while (!in.empty() && priority[in.top()] >= priority[src[i]]) { + builder += in.top(); + in.pop(); + } + in.push(src[i]); + } + } + if (builder[builder.size() - 1] != ' ') + builder += ' '; + while (!in.empty()) { + builder += in.top(); + in.pop(); + } + return builder; +} + +int eval(string src) { + stack in; + int num_builder = 0; + for (int i = 0; i < src.size(); i++) { + if (isdigit(src[i])) { + num_builder = num_builder * 10 + src[i] - '0'; + } else if (src[i] == ' ') { + in.push(num_builder); + num_builder = 0; + } else { + int y = in.top(); + in.pop(); + int x = in.top(); + in.pop(); + switch (src[i]) { + case '+': + in.push(x + y); + break; + case '-': + in.push(x - y); + break; + case '*': + in.push(x * y); + break; + case '/': + in.push(x / y); + break; + case '^': + in.push(pow(x, y)); + break; + } + } + } + return in.top(); +} + +int main() { + string str; + getline(cin, str); + cout << eval(in_order2post_order(str)) << endl; +}