- #include<iostream>
- #include<stack>
- using namespace std;
- class Calculator { // 整数的加减乘除运算器
- private:
- string Polish;
- long int result;
- public:
- Calculator() {
- }
- long int& getResult(string exp) {
- Polish.clear();
- stack<char> s1,s2;
- s1.push('#'); //以#号作为标记
- char temp;
- for(int i=0; i<exp.length(); i++) { //利用两个堆栈生成逆波兰式
- if (exp[i] >= '0' && exp[i] <= '9') {
- s2.push(exp[i]);
- } else if (exp[i] == '+' || exp[i] == '-' ||exp[i] == '*' ||exp[i] == '/') {
- s2.push('#');
- temp = s1.top();
- if(temp == '#'||(temp == '+' || temp == '-')&&(exp[i] == '*' ||exp[i] == '/')) {
- s1.push(exp[i]);
- } else {
- while (!(temp=='#'||temp == '(' || (temp == '+' || temp == '-') && (exp[i] == '*' ||exp[i] == '/'))) {
- s2.push(temp);
- s1.pop();
- temp = s1.top();
- }
- s1.push(exp[i]);
- }
- } else if(exp[i] == ')'|| exp[i] == '(') {
- if(exp[i] == '(') {
- s1.push(exp[i]);
- } else {
- temp = s1.top();
- while (temp != '(' ) {
- s2.push(temp);
- s1.pop();
- temp = s1.top();
- }
- s1.pop();
- }
- }
- }
- while(s1.top()!='#') {
- s2.push(s1.top());
- s1.pop();
- }
- for(;s2.size()>=1;) {
- Polish.push_back(s2.top());
- s2.pop();
- }
- long int temp2;
- long int temp3;
- long int temp1=0;
- stack<long int> s3;
- bool sign =0;
- for(int i = Polish.length()-1; i >= 0; i--) { //进行逆波兰式的运算
- if(Polish[i] >= '0' && Polish[i] <= '9') {
- temp1 = temp1*10 + Polish[i]-'0';
- sign = 1;
- }
- if((Polish[i] == '#'||Polish[i] == '+'||Polish[i] == '-'||Polish[i] == '*'||Polish[i] == '/')&&(sign == 1)||(i == 0&&sign == 1)) {
- if(sign == 1){
- s3.push(temp1);
- temp1 = 0;
- sign = 0;
- }
- }
- if(Polish[i] == '+'||Polish[i] == '-'||Polish[i] == '*'||Polish[i] == '/') {
- temp2 =s3.top();
- s3.pop();
- temp3 =s3.top();
- s3.pop();
- switch(Polish[i]) {
- case '+':
- s3.push(temp3+temp2);break;
- case '-':
- s3.push(temp3-temp2);break;
- case '*':
- s3.push(temp3*temp2);break;
- case '/':
- s3.push(temp3/temp2);break;
- }
- }
- }
- result = s3.top();
- return result;
- }
- };
- int main()
- {
- Calculator c; //对各种极端情况进行验证
- cout<<c.getResult("3")<<endl;
- cout<<c.getResult("((3+4)*5+6)*7")<<endl;
- cout<<c.getResult("1+2*3")<<endl;
- cout<<c.getResult("2*5+10")<<endl;
- cout<<c.getResult("3*(5+4)")<<endl;
- cout<<c.getResult("(4+5)*(2+2)")<<endl;
- cout<<c.getResult("1/2+1/2")<<endl;
- cout<<c.getResult("0+0")<<endl;
- cout<<c.getResult("4*5-7*8")<<endl;
- cout<<c.getResult("378+456-500*12/2")<<endl;
- cout<<c.getResult("((11*(12+13)*(14+15))+(16+17))*(18+19)")<<endl;
- cout<<c.getResult("4+5")<<endl;
- cout<<c.getResult("4")<<endl;
- cout<<c.getResult("77+44-22*33/11")<<endl;
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/0611201410903.html
来源: http://www.codesnippet.cn/detail/0611201410903.html