• Infix expression 计算 without '(' and ')'


    #include<iostream>
    #include<stack>
    #include<string>
    using namespace std;
    
    char compare(char tp, char op)
    {
    	if (((tp == '+' || tp == '-') && (op == '*' || op == '/')) || (tp == '#'))
    		return '<';
    	return '>';
    }
    
    int compute(int n1, int n2, char op)
    {
    	if (op == '+')
    		return n1 + n2;
    	else if (op == '-')
    		return n1 - n2;
    	else if (op == '*')
    		return n1*n2;
    	else if (op == '/')
    		return n2 / n1;
    }
    
    int main()
    {
    	stack<char>num;
    	stack<char>oper;
    
    	oper.push('#');
    
    	string s;
    	cin >> s;
    
    	for (int i = 0; i<s.length(); i++)
    	{
    		if (s[i] == '0' || s[i] == '1' || s[i] == '2' || s[i] == '3' || s[i] == '4' || s[i] == '5' || s[i] == '6' || s[i] == '7' || s[i] == '8' || s[i] == '9')
    			num.push(s[i]);
    		else
    		{
    			char comp = compare(oper.top(), s[i]);
    			if (comp == '<')
    				oper.push(s[i]);
    			else if (comp == '>')
    			{
    				int num1 = num.top()-'0';
    				num.pop();
    				int num2 = num.top()-'0';
    				num.pop();
    				int result = compute(num1, num2, oper.top());
    				num.push(result+'0');
    				oper.pop();
    				oper.push(s[i]);
    			}
    		}
    	}
    	
    	if (num.size() != 1)
    	{
    		while (oper.top() != '#')
    		{
    			int num1 = num.top()-'0';
    			num.pop();
    			int num2 = num.top()-'0';
    			num.pop();
    			int result = compute(num1, num2, oper.top());
    			num.push(result+'0');
    			oper.pop();
    		}
    	}
    
    	cout << num.top() << endl;
    
    	return 0;
    }
    

      

  • 相关阅读:
    贪心:SPOJ Backup Files
    杂题 SPOJ MOBILE2
    杂题 UVAoj 10000 Longest Paths
    杂题 UVAoj 107 The Cat in the Hat
    DP(斜率优化):HDU 3507 Print Article
    搜索(DLX): POJ 3074 3076 Sudoku
    DLX模板
    PHP代码优化技巧大盘点
    盘点PHP编程常见失误
    PHP Socket 编程详解
  • 原文地址:https://www.cnblogs.com/KennyRom/p/5979684.html
Copyright © 2020-2023  润新知