当前位置:网站首页>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;
}
};
边栏推荐
- Centos7 one click compilation to build MySQL script
- 【雅思阅读】王希伟阅读P2(阅读填空)
- Logback configuration file
- 多进程编程(四):共享内存
- 线程的启动与优先级
- 百数不断创新,打造自由的低代码办公工具
- Linux Software: how to install redis service
- [Luogu p4320] road meets (round square tree)
- Liad: the consumer end of micro LED products is first targeted at TVs above 100 inches. At this stage, it is still difficult to enter a smaller size
- Baidu AI Cloud takes the lead in building a comprehensive and standardized platform for smart cloud
猜你喜欢
Linux软件:如何安装Redis服务
logback配置文件
Rust字符串切片、结构体和枚举类
Sentry developer contribution Guide - configure pycharm
Solution to the problem of abnormal display of PDF exported Chinese documents of confluence
Redis21 classic interview questions, extreme pull interviewer
【AutoSAR 五 方法论】
Detailed explanation of pod life cycle
Linux Software: how to install redis service
1.11 - 总线
随机推荐
NC50528 滑动窗口
【雅思阅读】王希伟阅读P2(阅读填空)
NC24840 [USACO 2009 Mar S]Look Up
Nc50528 sliding window
form表单实例化
Nacos+openfeign error reporting solution
Briefly talk about other uses of operation and maintenance monitoring
[shutter] image component (the placeholder | transparent_image transparent image plug-in is loaded into the memory)
Liad: the consumer end of micro LED products is first targeted at TVs above 100 inches. At this stage, it is still difficult to enter a smaller size
2022上半年值得被看见的10条文案,每一句都能带给你力量!
University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement
腾讯云免费SSL证书扩展文件含义
Shell 实现文件基本操作(切割、排序、去重)
使用jenkins之二Job
百数不断创新,打造自由的低代码办公工具
[MCU project training] eight way answering machine
MySQL 23道经典面试吊打面试官
Sentry developer contribution Guide - configure pycharm
NC20806 区区区间间间
About qbytearray storage hexadecimal and hexadecimal conversion