当前位置:网站首页>leetcode-224:基本计算器
leetcode-224:基本计算器
2022-07-02 23:55:00 【菊头蝙蝠】
题目
题目连接
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
注意:不允许使用任何将字符串作为数学表达式计算的内置函数,比如 eval() 。
示例 1:
输入:s = "1 + 1"
输出:2
示例 2:
输入:s = " 2-1 + 2 "
输出:3
示例 3:
输入:s = "(1+(4+5+2)-3)+(6+8)"
输出:23
解题
方法一:栈
class Solution {
public:
int calculate(string s) {
int res=0,num=0,sign=1;
stack<int> st;
for(char c:s){
if(c>='0'&&c<='9'){
num=num*10+(c-'0');
}
else if(c=='+'||c=='-'){
res+=sign*num;
num=0;
sign=c=='+'?1:-1;
}
else if(c=='('){
st.push(res);
st.push(sign);
res=0;
sign=1;
}
else if(c==')'){
res+=sign*num;
num=0;
res*=st.top();
st.pop();
res+=st.top();
st.pop();
}
}
res+=sign*num;
return res;
}
};
边栏推荐
- FAQ | FAQ for building applications for large screen devices
- Hdu3507 (slope DP entry)
- Kubernetes simple introduction to writing YML
- 可下载《2022年中国数字化办公市场研究报告》详解1768亿元市场
- NC50528 滑动窗口
- [IELTS reading] Wang Xiwei reading P1 (reading judgment question)
- 【AutoSAR 二 AppL概述】
- [Luogu p4320] road meets (round square tree)
- About the practice topic of screen related to unity screen, unity moves around a certain point inside
- ftrace工具的介绍及使用
猜你喜欢
多进程编程(二):管道
【雅思阅读】王希伟阅读P1(阅读判断题)
Attributeerror: 'tuple' object has no attribute 'layer' problem solving
2022中国3D视觉企业(引导定位、分拣场景)厂商名单
【AutoSAR 五 方法论】
【AutoSAR 六 描述文件】
University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement
ftrace工具的介绍及使用
kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
1.12 - Instructions
随机推荐
File operation io-part2
Win10 多种方式解决无法安装.Net3.5的问题
关于XML一些介绍和注意事项
Hundreds of continuous innovation to create free low code office tools
NC50965 Largest Rectangle in a Histogram
redis21道经典面试题,极限拉扯面试官
【案例分享】让新时代教育发展与“数”俱进
Andorid gets the system title bar height
ftrace工具的介绍及使用
Nacos+openfeign error reporting solution
【日常训练】871. 最低加油次数
Multiprocess programming (V): semaphores
使用jenkins之二Job
Rust字符串切片、结构体和枚举类
Array common operation methods sorting (including ES6) and detailed use
Overlay of shutter (Pop-Up)
AttributeError: ‘tuple‘ object has no attribute ‘layer‘问题解决
NC24325 [USACO 2012 Mar S]Flowerpot
Sentry developer contribution Guide - configure pycharm
Rust string slicing, structs, and enumeration classes