链接: link.
链接: link.
定义两个栈:
nums:存放所有数字
ops:存放所有数字以外的操作
思路: 从前往后遍历当
举个🌰:
当我们读到字符串 1+2
时,当前栈操作为+
1+2
后面接-1
或+1
,满足上面黄色注释,因此我们把1+2
算出来,并把结果存入nums
栈中1+2
后面接*2
或/2
,不满足上面黄色注释,此时我们就不能把1+2
算出来细节:
完整代码
#include<bits/stdc++.h>
using namespace std;
//预处理函数
//替换空格、负数,(-2)->(0-2),(+4)->(0+4)
string replace(string& base, string src, string dst) {
int pos = 0, srclen = src.size(), dstlen = dst.size();
while ((pos = base.find(src, pos)) != string::npos) {
base.replace(pos, srclen, dst);
pos += dstlen;
}
return base;
}
//计算函数
void calc(stack<int> &nums, stack<char> &ops) {
if (nums.empty() || nums.size() < 2)
return;
if (ops.empty())
return;
int b = nums.top();
nums.pop();
int a = nums.top();
nums.pop();
char op = ops.top();
ops.pop();
int ans = 0;
if (op == '+') ans = a + b;
else if (op == '-') ans = a - b;
else if (op == '*') ans = a * b;
else if (op == '/') ans = a / b;
else if (op == '^') ans = (int)pow(a, b);
else if (op == '%') ans = a % b;
nums.push(ans);
}
int main() {
map<char,int> m;
//map存储符号优先级
m.insert(make_pair('+',1));
m.insert(make_pair('-',1));
m.insert(make_pair('*',2));
m.insert(make_pair('/',2));
m.insert(make_pair('%',3));
m.insert(make_pair('^',3));
//双栈
stack<char> ops;
stack<int> nums;
string s;
getline(cin,s);
//取出闲杂符号
s=replace(s," ","");
s=replace(s,"(-","(0-");
s=replace(s,"(+","(0+)");
int len=s.size();
nums.push(0);//防止第一个字符为符号
for(int i=0; i<len; i++) {
char c=s[i];
if(c=='(') {
ops.push(c);
} else if(c==')') {
while(!ops.empty()) {
if(ops.top()!='(') {
calc(nums,ops);
} else {
ops.pop();
break;
}
}
} else {
if(c>='0'&&c<='9') {
int u=0;
int j=i;
//整体取出数字
while(j<len&&s[j]>='0'&&s[j]<='9') {
u=u*10+(s[j++]-'0');
}
nums.push(u);
i=j-1;
} else {
while(!ops.empty()&&ops.top()!='(') {
char prev=ops.top();
if(m.find(prev)->second>=m.find(c)->second) {
calc(nums,ops);
} else {
break;
}
}
ops.push(c);
}
}
}
while(!ops.empty()) {
calc(nums,ops);
}
cout<<nums.top();
}
以后绝对不能栽在计算器上了,
思路来自LeetCode【宫水三叶】,三叶yyds。
错误描述: 在开发.net项目中,通过microsoft.ACE.oledb读取excel文件信息时,报...
项目中用到的一些特殊字符和图标 html代码 XML/HTML Code 复制内容到剪贴板 div ...
正则忽略大小写 – RegexOptions.IgnoreCase 例如: 复制代码 代码如下: Str = R...
工具:Eclipse,Oracle,smartupload.jar;语言:jsp,Java;数据存储:Oracle。...
4月11日20:30~22:00通过腾讯会议进行了第二次在线学习讨论我把学习笔记整理一下...
Elasticsearch 是通过 Lucene 的倒排索引技术实现比关系型数据库更快的过滤。特...
复制代码 代码如下: % URL="http://news.163.com/special/00011K6L/rss_newstop....
本文实例讲述了Laravel框架源码解析之反射的使用。分享给大家供大家参考,具体如...
上篇文章给大家介绍了 Java正则表达式匹配,替换,查找,切割的方法 ,接下来,...
DELETEFROMTablesWHEREIDNOTIN(SELECTMin(ID)FROMTablesGROUPBYName) Min的话保...