前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >表达式求值

表达式求值

作者头像
六月丶
发布2022-12-26 18:10:28
2540
发布2022-12-26 18:10:28
举报
文章被收录于专栏:六月-游戏开发六月-游戏开发

问题

给一个可包含+、-、*、/运算符和()的四则运算表达式,返回该表达式值(规定所有除都会是整数结果)。

解题思路

首先明确表达式定义

image.png
image.png
image.png
image.png

接下来按照这个定义写出对应递归代码即可。

代码

代码语言:javascript
复制
#include<iostream>
#include<sstream>
#include<string>
#include<cstdio>
typedef long long LL;
using namespace std;

stringstream ss;


LL factorValue();       //计算一个因子值 (因子由 整数 或 (表达式)构成)
LL termValue();         //计算一个项的值
LL expressionValue();       //计算一个表达式值


//计算一个表达式值
LL expressionValue(){
    LL result = termValue();
    bool more = true;
    while(more){
        char c = ss.peek();
        if(c == '+'){
            ss.get();
            result += termValue();
        }
        else if(c == '-'){
            ss.get();
            result -= termValue();
        }
        else
            more = false;
    }
    return result;
}

LL termValue(){
    LL result = factorValue();
    bool more = true;
    while(more){
        char c = ss.peek();
        if(c == '*' || c == '/'){
            ss.get();
            result = c == '*' ? result * factorValue() : result / factorValue();
        }
        else more = false;
    }

    return result;
}

LL factorValue(){
    LL result = 0;
    char c = ss.peek();
    if(c == '('){
        ss.get();
        result = expressionValue();
        ss.get();       //拿掉右括号
    }
    else{
        //读取一个整数
        int num;
        while(ss.peek() >= '0' && ss.peek() <= '9'){
            num = ss.get() - '0';
            result = result * 10 + num;
        }
    }
    return result;
}
int main(){
    //io流换成string流是为了模拟题目要求直接处理给定字符串情况。
    string s;
    cin >> s;
    ss << s;
    cout << expressionValue() << endl;

    return 0;
}
//(1+2)*2+45*2

参考视频:https://www.icourse163.org/learn/PKU-1001894005?tid=1468226518#/learn/content?type=detail&id=1249931106

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022 年 07 月,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题
  • 解题思路
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档