#include <cmath>
#include <iostream>
using namespace std;
const int N = 255;
int n[N] = {0};
char c[N] = {0};
bool Priority(char ch1, char ch2)//判断ch1是否比ch2优先级高
{
    if (ch1 == '^')//优先级最高 
	{
        return true;
    }
    if (ch2 == '^')//优先级最高 
	{
        return false;
    }
    if (ch2 == ')')//优先级最低 
	{
        return true;
    }
    if (ch1 == '-' || ch1 == '+')//优先级较低 
	{
        if (ch2 == '-' || ch2 == '+') 
		{
            return true;
        }
        return false;
    }
    if (ch1 == '*' || ch1 == '/')//优先级较高 
	{
        return true;
    }
    return false;
}
 
int calc(int a, int b, char op)
{
    switch (op) 
	{
        case '+':
            return a + b;
        case '-':
            return a - b;
        case '*':
            return a * b;
        case '/':
            return a / b;
        case '^':
            return pow(a, b);
    }
    return 0;
}
int main()
{
    char ch = 0;
    int a = 0, b;
    int ntop = 0, ctop = 0;
    while (1)
	{
		cin.get(ch);
        switch (ch) 
		{
            case '+':
            case '-':
            case '*':
            case '/':
            case '^':
                n[ntop++] = a;
                while (ctop > 0 && Priority(c[ctop - 1], ch)) 
				{
                    b = n[--ntop];
                    a = n[--ntop];
                    n[ntop++] = calc(a, b, c[--ctop]);
                }
                c[ctop++] = ch;
                a = 0;
                break;
            case '(':
                c[ctop++] = ch;
                break;
            case ')':
                n[ntop++] = a;
                while (ctop > 0 && c[ctop - 1] != '(' && Priority(c[ctop - 1], ch)) 
				{
                    b = n[--ntop];
                    a = n[--ntop];
                    n[ntop++] = calc(a, b, c[--ctop]);
                }
                if (c[ctop - 1] == '(')//弹出( 
				{
                    a = n[--ntop];
                    ctop--;
                }
                break;
            default:
                if (ch >= '0' && ch <= '9') 
				{
                    a = a * 10 + (ch - '0');
                } 
				else//结束 
				{
                    n[ntop++] = a;
                    while (ctop > 0) 
					{
                        b = n[--ntop];
                        a = n[--ntop];
                        n[ntop++] = calc(a, b, c[--ctop]);
                    }
                    cout << n[--ntop];
                    return 0;
                }
                break;
        }
    }
    return 0;
}

1 comments

  • 1

Information

ID
841
Time
1000ms
Memory
256MiB
Difficulty
7
Tags
# Submissions
109
Accepted
24
Uploaded By