当前位置:网站首页>224. 基本计算器-递归法
224. 基本计算器-递归法
2022-07-21 23:07:00 【Mr Gao】
224. 基本计算器
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
注意:不允许使用任何将字符串作为数学表达式计算的内置函数,比如 eval() 。
示例 1:
输入:s = “1 + 1”
输出:2
示例 2:
输入:s = " 2-1 + 2 "
输出:3
示例 3:
输入:s = “(1+(4+5+2)-3)+(6+8)”
输出:23
代码可能稍微复杂点,思路还是比较清晰的,解题代码如下:
long long f(char *s,int *pos){
long long re=0;
while(s[(*pos)]>='0'&&s[(*pos)]<='9'){
re=re*10+s[(*pos)]-'0';
(*pos)++;
}
return re;
}
int calculate2(char *s,int *pos){
long long len=strlen(s);
long long optstack[100];
long long otop=0;
long long re=0;
optstack[otop++]=1;
while(s[*pos]!='\0'){
if(s[*pos]==' '){
(*pos)++;
continue;
}
if(s[(*pos)]=='+'){
optstack[otop++]=1;
(*pos)++;
}
else if(s[(*pos)]=='-'){
optstack[otop++]=-1;
(*pos)++;
}
else if(s[*pos]=='('){
(*pos)++;
long long rez=calculate2(s,pos);
re=re+optstack[--otop]*rez;
printf(" %c ",s[otop]);
}
else if(s[(*pos)]==')'){
(*pos)++;
return re;
}
else{
long long ret=f(s,pos);
re=re+optstack[--otop]*ret;
}
}
return re;
}
int calculate(char * s){
long long *pos=(int *)malloc(sizeof(long long));
*pos=0;
long long re=calculate2(s,pos);
printf("%d ",re);
return re;
}
边栏推荐
- Elemen when clicking, modify the playback index of the walking lantern
- Typescript - syntax introduction
- Qt中的坐标系统
- ARM+SD2405 IIC_ RTC driver writing and IIC communication protocol
- Use the browser plug-in to run JS to delete the "disable copy" function of a specific website
- 图表绘制总结
- 李彦宏:无人驾驶是人类创造价值最大的创新
- 2022/07/20---把字符串转换成整数; 滑动窗口的最大值
- 数组和对象的一些方法
- ARM+SD2405 IIC_RTC驱动编写及IIC通讯协议
猜你喜欢
Use the browser plug-in to run JS to delete the "disable copy" function of a specific website
边框动态效果实现
JVM类加载和垃圾回收
(ICCV-2021)TransReID:基于transformer的目标重识别
深入理解完美哈希
PMP practice once a day | don't get lost in the exam -7.21
“新能源+储能“从数字孪生开始,图扑将智慧电力做到极致
Service (LB) and managed pod
What if Lao Xue's host disk space is full
如何正确使用call、bind、apply
随机推荐
[MySQL]索引事务
[MySQL must know and know] stored procedure | cursor
2022/07/20---把字符串转换成整数; 滑动窗口的最大值
Solve the problem of using external files in Google Labs
Elephant Swap的LaaS方案迅速崛起,构建全新DeFi2.0协议
ClickHouse引擎之-MaterializeMYSQL
iTOP-RK3568开发板Debian系统功能测试-有线网测试
(ICLR-2021)一幅图像相当于16X16个words:大规模图像识别的Transformer
MySQL: character sets and comparison rules
El pinut number cancel number operation symbol
Qt5中创建及使用自定义插件遇到的一些问题
小程序项目总结
Some problems encountered in creating and using custom plug-ins in Qt5
智能仪器仪表行业数字化供应链管理系统:加速企业智慧供应链平台转型
Elephant Swap的LaaS方案优势分析,致eToken表现强势
The difference between EM and REM
Qt 使用 Google Breakpad 捕获程序崩溃报告(dump文件)
Applet project summary
The difference between join on followed by condition and where followed by condition
SQL statement. After grouping, the group is sorted according to the datetime field, the latest record in the group is retained, and other items are deleted. (used to eliminate duplicate data within th