当前位置:网站首页>Leetcode-224: basic calculator
Leetcode-224: basic calculator
2022-07-03 00:47:00 【Chrysanthemum headed bat】
leetcode-224: Basic calculator
subject
Topic linking
Here's a string expression for you s , Please implement a basic calculator to calculate and return its value .
Be careful : Any built-in functions that evaluate strings as mathematical expressions are not allowed , such as eval() .
Example 1:
Input :s = "1 + 1"
Output :2
Example 2:
Input :s = " 2-1 + 2 "
Output :3
Example 3:
Input :s = "(1+(4+5+2)-3)+(6+8)"
Output :23
Problem solving
Method 1 : Stack
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;
}
};
边栏推荐
- 线程的启动与优先级
- 简单聊聊运维监控的其他用途
- 腾讯云免费SSL证书扩展文件含义
- [shutter] image component (load network pictures | load static pictures | load local pictures | path | provider plug-in)
- Vulkan performance and refinement
- 1.11 - 总线
- 【AutoSAR 十二 模式管理】
- 测试右移:线上质量监控 ELK 实战
- 【AutoSAR 十一 通信相关机制】
- LeedCode1480. Dynamic sum of one-dimensional array
猜你喜欢
Teach you JDBC hand in hand -- structure separation
AttributeError: ‘tuple‘ object has no attribute ‘layer‘问题解决
University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement
Introduction of UART, RS232, RS485, I2C and SPI
【AutoSAR 一 概述】
kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
Rust所有权(非常重要)
测试右移:线上质量监控 ELK 实战
Nacos+openfeign error reporting solution
[shutter] image component (load network pictures | load static pictures | load local pictures | path | provider plug-in)
随机推荐
Lex & yacc & bison & flex configuration problems
Kubernetes resource object introduction and common commands (V) - (NFS & PV & PVC)
ftrace工具的介绍及使用
JSON conversion tool class
【雅思阅读】王希伟阅读P2(阅读填空)
Nacos+openfeign error reporting solution
百数不断创新,打造自由的低代码办公工具
Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
Use Jenkins II job
Multiprocess programming (II): Pipeline
1.12 - Instructions
2022 list of manufacturers of Chinese 3D vision enterprises (guided positioning and sorting scenes)
【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议
leetcode-241:为运算表达式设计优先级
Linux Software: how to install redis service
Linux软件:如何安装Redis服务
Shell implements basic file operations (cutting, sorting, and de duplication)
【AutoSAR 九 C/S原理架构】
LeedCode1480. Dynamic sum of one-dimensional array
AttributeError: ‘tuple‘ object has no attribute ‘layer‘问题解决