基本计算器,参考博客:https://www.cnblogs.com/grandyang/p/4606334.html
基本计算器1:leetcode224题
class Solution {
public:
int calculate(string s) {
int res=0,num=0,sign=1,n=s.size();
for(int i=0;i<n;++i)
{
char c=s[i];
if(c>='0'&&c<='9')
{
num=10*num+(c-'0');
}
else if(c=='(')
{
int j=i,cnt=0;
for(;i<n;++i)
{
if(s[i]=='(') ++cnt;
if(s[i]==')') --cnt;
if(cnt==0) break;
}
num=calculate(s.substr(j+1,i-j-1));
}
if(c=='+'||c=='-'||i==n-1)
{
res+=sign*num;
num=0;
sign=(c=='+')?1:-1;
}
}
return res;
}
};
基本计算器2:leetcode227题
class Solution {
public:
int calculate(string s) {
int res=0,curRes=0,num=0,n=s.size();
char op='+';
for(int i=0;i<n;++i)
{
char c=s[i];
if(c>='0'&&c<='9')
num=10*num+(c-'0');
if(c=='+'||c=='-'||c=='*'||c=='/'||i==n-1)
{
switch(op)
{
case '+': curRes+=num;break;
case '-': curRes-=num;break;
case '*': curRes*=num;break;
case '/': curRes/=num;break;
}
if(c=='+'||c=='-'||i==n-1)
{
res+=curRes;
curRes=0;
}
num=0;
op=c;
}
}
return res;
}
};
基本计算器3:leetcode772题
相比于12两道题的综合 1是只有加减和括号,2是有加减乘除无括号,3是有加减乘除也有括号
class Solution {
public:
int calculate(string s) {
int n = s.size(), num = 0, curRes = 0, res = 0;
char op = '+';
for (int i = 0; i < n; ++i) {
char c = s[i];
if (c >= '0' && c <= '9') {
num = num * 10 + c - '0';
} else if (c == '(') {
int j = i, cnt = 0;
for (; i < n; ++i) {
if (s[i] == '(') ++cnt;
if (s[i] == ')') --cnt;
if (cnt == 0) break;
}
num = calculate(s.substr(j + 1, i - j - 1));
}
if (c == '+' || c == '-' || c == '*' || c == '/' || i == n - 1) {
switch (op) {
case '+': curRes += num; break;
case '-': curRes -= num; break;
case '*': curRes *= num; break;
case '/': curRes /= num; break;
}
if (c == '+' || c == '-' || i == n - 1) {
res += curRes;
curRes = 0;
}
op = c;
num = 0;
}
}
return res;
}
};
基本计算器变体:把常用的逻辑计算与或非转换成结果
比如"!1|0&1"和"!1|(0&1)"这种,优先级是!>&>| 四则运算有两个优先级(如果加上括号是三个),与或非这种就是三种优先级,加上括号会出现四种优先级:输入只会出现01()!|&这几种字符:
int calculate(string s) {
int n = s.size(), num = 0, curRes = 0, res = 0;
char op = '|';
for (int i = 0; i < n; ++i) {
char c = s[i];
if (c >= '0' && c <= '9') {
num = c - '0';
}
else if (c == '(') {
int j = i, cnt = 0;
for (; i < n; ++i) {
if (s[i] == '(') ++cnt;
if (s[i] == ')') --cnt;
if (cnt == 0) break;
}
num = calculate(s.substr(j + 1, i - j - 1));
}
if (c =='!'&&i+1<n)
{
s[i + 1] = (s[i + 1] == '0' ? '1' : '0');
}
if (c == '|' || c == '&' || i == n - 1) {
switch (op) {
case '|': curRes = curRes|num; break;
case '&': curRes = curRes# break;
}
/*if (c == '|' || i == n - 1) {
res = res|curRes;
curRes = 0;
}*/
op = c;
//num = 0;
}
}
return curRes;
}
int main() {
//string s = "1&0|0&1";
//string s = "!0&1|0";
string s = "!0&1|0";
//string s = "((!0&1))|0";
//string s = "";
cout << s;
int res = calculate(s);
cout << res;
cout << "done";
return res;
}
代码可能会有错误,欢迎指正,是仿照grandyang的解法写出来的。