Leetcoe224 计算器
发布日期:2022-09-10 02:26:32
浏览次数:8
分类:技术文章
本文共 2047 字,大约阅读时间需要 6 分钟。
class Solution { public: //+-*计算 int func(int a,int b,char op){ if(op=='+') return a+b; else if(op=='-') return a-b; else if(op=='*') return a*b; else return a/b; return 0; } //运算符优先级 int getpriority(char op){ if(op=='+'||op=='-') return 1; else return 2; return 0; } //越界或者遇到左括号返回 vector help(string s,int index){ stack nums;//操作数栈 stackops;//运算符栈 int i=index; while(i ='0'&&s[i]<='9'){ //当前为数字,继续寻找数字,然后将操作数入栈 int cur=0; while(s[i] >= '0' && s[i] <= '9') cur = cur * 10 + (s[i++] - '0'); nums.push(cur); }else if(s[i]!='('){ //当前为运算符,判断优先级 if(nums.empty()&&s[i]=='-'){ nums.push(0); }else if(ops.empty()||getpriority(s[i])>getpriority(ops.top())){ ops.push(s[i++]); }else{ while(!ops.empty()&&getpriority(s[i])<=getpriority(ops.top())){ int num1=nums.top(); nums.pop(); int num2=nums.top(); nums.pop(); char op=ops.top(); ops.pop(); int res=func(num2,num1,op); nums.push(res); } ops.push(s[i++]); } }else{ //遇到左括号,继续递归,将子过程返回的结果压入栈中,当前位置为子过程结束位置的下一个位置 auto res=help(s,i+1); nums.push(res[0]); i=res[1]+1; } } while(!ops.empty()){ int num1=nums.top(); nums.pop(); int num2=nums.top(); nums.pop(); char op=ops.top(); ops.pop(); int res=func(num2,num1,op); nums.push(res); } return { nums.top(),i}; } int calculate(string s) { return help(s,0)[0]; }};
转载地址:https://blog.csdn.net/qq_39240107/article/details/125896733 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
表示我来过!
[***.240.166.169]2024年04月11日 13时44分06秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Python 爬虫面试题 170 道:2019 版
2019-04-26
歪门邪道
2019-04-26
我的前六年程序生涯
2019-04-26
知识地图
2019-04-26
罗马总会建成
2019-04-26
程序通过技术赚钱的八个途径
2019-04-26
我在爬坡阶段
2019-04-26
大疆机甲大师教育机器人Python开发:中文命名变量初尝试
2019-04-26
大疆机甲大师教育机器人Python开发:API中文化初尝试
2019-04-26
大疆机甲大师Python开发: 两只老虎
2019-04-26
大疆机甲大师教育机器人Python API中文化之一:枪亮枪暗
2019-04-26
大疆机甲大师教育机器人Python API中文化之二:LED闪烁
2019-04-26
大疆 RoboMaster 机甲大师官方刚刚开通”机甲小 S 实验室”知乎专栏
2019-04-26
大疆机甲大师教育机器人Python API中文化之三:底盘灯效
2019-04-26
大疆机甲大师教育机器人Python API中文化之四五:云台灯效,指定序号
2019-04-26
大疆机甲大师教育机器人Python API中文化之六:关灯
2019-04-26
“中文编程”知乎专栏两岁了——山雨欲来风满楼
2019-04-26
大疆机甲大师Python API之七:做个闹钟
2019-04-26
【意外走向】大疆机甲大师Python API之八:计时——为性能测试展开1000次循环
2019-04-26