#38422: don't try


yp11251273@yphs.tp.edu.tw (704-31張鈞勉)

學校 : 臺北市私立延平高級中學
編號 : 239174
來源 : [203.72.178.1]
最後登入時間 :
2024-04-16 17:46:03
a017. 五則運算 | From: [203.72.178.1] | 發表日期 : 2023-11-21 17:30

#include <bits/stdc++.h> using namespace std; int main() { string s, c; while(getline(cin, s)) { stack <string> st; vector <string> ans; stringstream ss; ss << s; while(ss >> c) { if(c == ")") { while(st.top() != "(") { ans.push_back(st.top()); st.pop(); } st.pop(); } else if(c == "(") { st.push("("); } else if(c == "*" || c == "/" || c == "%") { while(!st.empty() && (st.top() == "*" || st.top() == "/" || st.top() == "%")) { ans.push_back(st.top()); st.pop(); } st.push(c); } else if(c == "+" || c == "-") { while(!st.empty() && (st.top() == "*" || st.top() == "/" || st.top() == "+" || st.top() == "-" || st.top() == "%")) { ans.push_back(st.top()); st.pop(); } st.push(c); } else { ans.push_back(c); } } while(!st.empty()) { ans.push_back(st.top()); st.pop(); } stack <int> st2; for(string x : ans) { if(x == "+" || x == "-" || x == "/" || x == "*" || x == "%") { signed int sc = st2.top(); st2.pop(); // 題目說是有號整數 signed int ft = st2.top(); st2.pop(); if(x == "+") st2.push(ft+sc); if(x == "-") st2.push(ft-sc); if(x == "*") st2.push(ft*sc); if(x == "/") st2.push(ft/sc); if(x == "%") st2.push(ft%sc); } else { st2.push(stoi(x)); } } cout << st2.top() << '\n'; } }

 
ZeroJudge Forum