19009 后缀表达式

思路

  1. **输入处理**:读取输入的后缀表达式,去掉末尾的`@`符号。

  2. **使用栈计算后缀表达式**:

  • 遍历表达式中的每个字符。

  • 如果是数字,压入栈中。

  • 如果是运算符,从栈中弹出两个数字进行运算,并将结果压入栈中。

  1. **输出结果**:栈中最后剩下的数字即为表达式的结果。

伪代码

```

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++代码

cpp 复制代码
#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. **输出结果**:栈中最后剩下的数字即为结果。

相关推荐
总爱写点小BUG几秒前
打印不同的三角形(C语言)
java·c语言·算法
yaoh.wang2 分钟前
力扣(LeetCode) 27: 移除元素 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·双指针
2401_8414956412 分钟前
【自然语言处理】中文 n-gram 词模型
人工智能·python·算法·自然语言处理·n-gram·中文文本生成模型·kneser-ney平滑
San3033 分钟前
从零到一:彻底搞定面试高频算法——“列表转树”与“爬楼梯”全解析
javascript·算法·面试
F_D_Z39 分钟前
最长连续序列(Longest Consecutive Sequence)
数据结构·算法·leetcode
ss27340 分钟前
Java并发编程:DelayQueue延迟订单系统
java·python·算法
SHERlocked9342 分钟前
摄像头 RTSP 流视频多路实时监控解决方案实践
c++·后端·音视频开发
JHC00000042 分钟前
118. 杨辉三角
python·算法·面试
WolfGang0073211 小时前
代码随想录算法训练营Day50 | 拓扑排序、dijkstra(朴素版)
数据结构·算法
业精于勤的牙1 小时前
浅谈:算法中的斐波那契数(四)
算法