acwing 表达式求值, 题号3302
#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#include <stack>
using namespace std;
stack<int> num;
stack<char> op;
void calc()
{
int b = num.top(); num.pop();
int a = num.top(); num.pop();
char c = op.top(); op.pop();
if (c == '+') num.push(a + b);
else if (c == '-') num.push(a - b);
else if (c == '*') num.push(a * b);
else num.push(a / b);
}
int main()
{
unordered_map<char, int> pr { {'+', 1}, {'-' , 1}, {'*', 2}, {'/', 2} };
string st;
cin >> st;
getchar();
for (int i = 0; i < st.size(); i ++)
{
char c = st[i];
if (isdigit(c))
{
int x = 0, j = i;
while (j < st.size() && isdigit(st[j]))
x = x * 10 + st[j ++] - '0';
i = j - 1;
num.push(x);
}
else if (c == '(') op.push(c);
else if (c == ')')
{
while (op.top() != '(')calc();
op.pop();
}
else
{
while (op.size() && op.top() != '(' && pr[op.top()] >= pr[c]) calc();
op.push(c);
}
}
while (op.size()) calc();
cout << num.top() << endl;
return 0;
}
import java.util.HashMap;
import java.util.Scanner;
import java.util.Stack;
public class Main {
private static Stack<Integer> num = new Stack<Integer>();
private static Stack<Character> op = new Stack<Character>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String st = scanner.nextLine();
HashMap<Character, Integer> pr = new HashMap<>();
pr.put('+', 1);
pr.put('-', 1);
pr.put('*', 2);
pr.put('/', 2);
for (int i = 0; i < st.length(); i++)
{
char c = st.charAt(i);
if (isdigit(c))
{
int x = 0, j = i;
while (j < st.length() && isdigit(st.charAt(j)))
{
x = x * 10 + st.charAt(j++) - '0';
}
i = j - 1;
num.push(x);
}
else if (c == '(') {
op.push(c);
}
else if (c == ')') {
while (op.peek() != '(') {
calc();
}
op.pop();
}
else
{
while (!op.empty() && op.peek() != '(' && pr.get(op.peek()) >= pr.get(c))
{
calc();
}
op.push(c);
}
}
while (!op.empty())
{
calc();
}
System.out.println(num.peek());
}
public static boolean isdigit(char c) {
if (c >= '0' && c <= '9') return true;
else {
return false;
}
}
public static void calc()
{
int b = num.pop();
int a = num.pop();
char c = op.pop();
if (c == '+') {
num.push(a + b);
}
else if (c == '-') {
num.push(a - b);
}
else if (c == '*') {
num.push(a * b);
}
if (c == '/') {
num.push(a / b);
}
}
}