首页 > 其他分享 >表达式求值

表达式求值

时间:2022-11-30 22:14:45浏览次数:31  
标签:ops top while mp 求值 表达式 size

给定一个表达式,其中运算符仅包含 +,-,*,/(加 减 乘 整除),可能包含括号,请你求出表达式的最终值。

#include <iostream>
#include <stack>
#include <unordered_map>
using namespace std;
unordered_map <char, int> mp;
stack<int> nums;
stack<char> ops;

void init () {
    mp['('] = 0;
    mp['+'] = mp['-'] = 1;
    mp['*'] = mp['/'] = 2;
}

bool isd (char c) {
    return '0' <= c && c <= '9';
}

void cal () {
    char op = ops.top(); ops.pop();
    int b = nums.top(); nums.pop();
    int a = nums.top(); nums.pop();
    
    if (op == '+') nums.push(a + b);
    else if (op == '-') nums.push(a - b);
    else if (op == '*') nums.push(a * b);
    else nums.push(a / b);
} 

int main() {
    init();
    string s;
    cin >> s;
    for (int i = 0; i < s.size(); i++) {
        char c = s[i];
        if (isd(c)) {
            int j = i, x = 0;
            while (j < s.size() && isd(s[j])) x = x * 10 + s[j++] - '0';
            nums.push(x);
            i = --j;
        }
        else if (c == '(') ops.push(c);
        else if (c == ')') {
            while (ops.top() != '(') cal();
            ops.pop();
        }
        else {
            while (ops.size() && ops.top() != '(' && mp[ops.top()] >= mp[c]) cal();
            ops.push(c);
        }
    }
    
    while (ops.size()) cal();
    cout << nums.top() << endl;
    return 0;
}

  

标签:ops,top,while,mp,求值,表达式,size
From: https://www.cnblogs.com/leetothemoon/p/16939904.html

相关文章

  • aop切点定义表达式详解
    目录1.execution2.within3.this4.target5.args6.bean7.@args8.@target9.@within10.@annotation11.组合表达式1.execution可以匹配到方法级别格式如下:execution(方法访......
  • Lambda表达式简介
    什么是Lambda?:java8的新特性。是个匿名函数。为什么使用Lambda?:可以对接口进行非常简洁的实现。使用Lambda表达式来实现接口Comparatorcomparator3=(a,b)->a-b;......
  • go 正则表达式
    funcmain(){ line:="2022/11/2519:32<DIR>目录" reg:=regexp.MustCompile(`([\d/]+)\s+(\d+:\d+)\s+(<DIR>)\s+(.*)`) ifreg==nil{ panic(......
  • 使用正则表达式处理字符串
    参考代码:mportrestrInput='310.1'strList=re.findall('^[\-\+]?\d+\.?\d+$',strInput)print(strList)strInput2='aa310.0.1'strList2=re.search('[\-\+......
  • Python高级-正则表达式-笔记
    1.re模块操作在Python中需要通过正则表达式对字符串进行匹配的时候,可以使用一个模块,名字为re1.re模块的使用过程#coding=utf-8#导入re模块importre#使用mat......
  • 数据结构实验之栈与队列二:一般算术表达式转换成后缀式 sdut-oj
    #include<stdio.h>#include<stdlib.h>#defineSTACK_INIT_SIZE100#defineSTACKINCREMENT100typedefstruct{  char*base;  ......
  • 常量表达式
    1、常量表达式是指值不会改变,并且在编译过程中就能得到计算结果的表达式。2、把变量定义成constexpr的,可以让编译器来验证它是否是常量表达式,如果初始化使用了非常量表达......
  • 正则表达式的Wed验证应用(40)
    电子邮件地址的校验<?php/*校验邮件地址*/functioncheckMail($email){//用户名,由“\w”格式字符、“-”或“.”组成$email_name="\w|(\w[-.\w]*\w)";//域名中的第一段,规......
  • aop切点表达式写法
    表达式语法excution([修饰符]返回值类型包名.类名.方法名(参数))* 访问修饰符可以省略* 返回值类型、包名、类名、方法名、可以使用星号*代......
  • c# paddleorcsharp批量图片文字识别,拖拽实现,正则表达式提取
    usingPaddleOCRSharp;usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;......