当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢
深度剖析数据在内存中的存储
【AutoSAR 八 OS】
【AutoSAR 四 BSW概述】
2022 list of manufacturers of Chinese 3D vision enterprises (guided positioning and sorting scenes)
Baidu AI Cloud takes the lead in building a comprehensive and standardized platform for smart cloud
MySQL 23 classic interview hanging interviewer
Use Jenkins II job
Rust所有权(非常重要)
Rust字符串切片、结构体和枚举类
Vulkan-性能及精细化
随机推荐
Graduation summary
Automated defect analysis in electron microscopic images-论文阅读笔记
[Luogu p4320] road meets (round square tree)
【luogu P4320】道路相遇(圆方树)
FAQ | FAQ for building applications for large screen devices
Problèmes de configuration lex & yacc & Bison & Flex
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
Pageoffice - bug modification journey
Array common operation methods sorting (including ES6) and detailed use
Extension of flutter
Attributeerror: 'tuple' object has no attribute 'layer' problem solving
File operation io-part2
Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
Vulkan practice first bullet
1.12 - Instructions
1.11 - 总线
Shell implements basic file operations (cutting, sorting, and de duplication)
奥斯陆大学:Li Meng | 基于Swin-Transformer的深度强化学习
Multiprocess programming (V): semaphores
【AutoSAR 十 IO架构】