当前位置: 首页 > news >正文

19009 后缀表达式

### 思路
1. **输入处理**:读取输入的后缀表达式,去掉末尾的`@`符号。
2. **使用栈计算后缀表达式**:
   - 遍历表达式中的每个字符。
   - 如果是数字,压入栈中。
   - 如果是运算符,从栈中弹出两个数字进行运算,并将结果压入栈中。
3. **输出结果**:栈中最后剩下的数字即为表达式的结果。

### 伪代码
```
function evaluate_postfix(expression):
    stack = []

    for token in expression.split():
        if token is a digit:
            stack.push(int(token))
        else if token is an operator:
            b = stack.pop()
            a = stack.pop()
            result = perform_operation(a, b, token)
            stack.push(result)

    return stack.pop()

function perform_operation(a, b, operator):
    if operator == '+':
        return a + b
    if operator == '-':
        return a - b
    if operator == '*':
        return a * b
    if operator == '/':
        return a / b

function main():
    while input is not EOF:
        expression = read_input().strip('@')
        result = evaluate_postfix(expression)
        print(result)
```

### C++代码
 

#include <iostream>
#include <stack>
#include <sstream>
#include <string>int main() {std::string input;std::getline(std::cin, input);std::stack<int> s;std::istringstream iss(input);std::string token;while (iss >> token) {if (token == "@") {break;} else if (isdigit(token[0])) {s.push(std::stoi(token));} else {for (char op : token) {if (op == '@') {break;}int b = s.top(); s.pop();int a = s.top(); s.pop();if (op == '+') {s.push(a + b);} else if (op == '-') {s.push(a - b);} else if (op == '*') {s.push(a * b);} else if (op == '/') {s.push(a / b);}}}}std::cout << s.top() << std::endl;return 0;
}

### 总结
1. **输入处理**:读取并去掉末尾的`@`符号。
2. **使用栈计算后缀表达式**:遍历表达式,数字压栈,运算符弹出两个数字计算并压栈。
3. **输出结果**:栈中最后剩下的数字即为结果。


http://www.mrgr.cn/news/50233.html

相关文章:

  • 解析 MySQL 查询优化:提升性能的十个关键策略
  • Vulnhub:DarkHole_2
  • 10月下半记录
  • C++面试速通宝典——27
  • spring boot热部署
  • VMware免安装直接使用Win7成品虚拟机
  • 若依前后端分离版本el-select下拉框字典如何设置默认值。
  • java中常量
  • 【C语言】动态内存管理及相关笔试题
  • Vmware一步安装win7系统
  • mysql集群-主库从库配置--主从库分离
  • 双11购物节,淘宝、京东薅羊毛~红包攻略
  • IWO-Kmeans聚类 | MATLAB实现IWO-Kmeans侵入性杂草优化K均值聚类算法
  • 安装transformer(配置pytorch环境;安装transformers库)
  • LeetCode Hot100 - 双指针篇
  • 城市形态计算方法
  • agent介绍
  • 量化投资学习
  • P1493 分梨子(NW)
  • 解决方案:“<”not supported between instances instances of “int” and “str”