最近面试了一家公司,笔试成绩一塌糊涂,没想到人家没否定我哈哈,给我两天时间让我写一个计算器出来,核心代码部分就在这了,可能还有考虑不周的情况,多多指教。
#include<bits/stdc++.h>
using namespace std;int fun(int x, char p, int y)
{if(p == '+')return x + y ;else if(p == '-')return x - y ;else if(p == '*')return x * y ;elsereturn x / y ;
}//计算不带括号的表达式
int clc_with_no_kuohao(string s)
{vector<char> c_stack; //存放运算符 vector<int> n_stack; //存放数字 bool flag = false; //此变量的作用是判断a+-b的情况 if(s[0] == '+')//去掉第一个正号 s.erase(s.begin());for(int i = 0; i < s.size(); i++){if(s[i] >= '0' && s[i] <= '9') //如果是数字 n_stack.push_back(s[i] - '0'),flag = false;else //如果是字符 {if(s[i] == '/' || s[i] == '*') //乘除 {int a = n_stack.back(); n_stack.pop_back();if(s[i+1] == '-') // a*-b 或 a/-b n_stack.push_back(fun(a, s[i], -(s[i+2]-'0'))),i+=2;elsen_stack.push_back(fun(a, s[i], s[i+1]-'0')),i++;flag = false;}else //加减 {if( i == 0 && s[0] == '-') //第一个负号 n_stack.push_back( 0 - (s[1] - '0')), i++;else if(s[i] == '-' && flag) //遇到负号 (a+-b 的情况 ){n_stack.push_back(0 - (s[i+1] - '0'));flag = false; i++;}elsec_stack.push_back(s[i]),flag = true; //不是第一位 } }}int res = n_stack[0];for(int i = 1, j = 0; i < n_stack.size(); i++) //加减计算 res = fun(res, c_stack[j++], n_stack[i]);return res;} void remove_kuohao(string &s, int index) //去掉括号
{int start = s.find('(', index);if(start == -1)return ;for(int i = start + 1; i < s.length(); i++){if(s[i] == ')')break;elseif(s[i] == '(') //如果里面有子括号 {remove_kuohao(s, i); // 递归处理 break;}}int len = s.find(')', start + 1) - start + 1; //找到右括号的位置 int temp = clc_with_no_kuohao(s.substr(start+1, len-1)); //调用 clc_with_no_kuohao 计算括号里面表达式的值 s.replace(start, len, to_string(temp)); //转换成字符串替换原来的(xxx) (有可能是个负数) start = s.find('(', start); //继续往后寻找左括号 if(start != -1)remove_kuohao(s, start);}int main()
{string s;cin >> s;remove_kuohao(s, 0);cout << s << endl ;cout << clc_with_no_kuohao(s) << endl;return 0;
}/*
-1-2*3-4*5+3
1*2+4/2+3-1-2*3-4*5+(3*(1+2)+2)*2+3+2(2-1)*2-1*(1+1)+((1-2)*2-1*(1+1))*13*(1-2)
3+-2
3*-2
2+(((2-3)))+1
4/2+2*(6/3)*3
4/2*3+2-3*(1-2)
*/