Evaluate Reverse Polish Notation

2257 단어 eval
Evaluate Reverse Polish Notation
제목 링크:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/  Evaluate the value of an arithmetic expression in Reverse Polish Notation.
  Valid operators are +, -, *, /. Each operand may be an integer or another expression.
  Some examples:   ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9   ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
  • 제목 대의:역 폴란드 표현 식 을 지정 하여 이 표현 식 의 값 을 구하 십시오
  • 사고:역 폴란드 표현 식 자체 에 괄호 가 필요 없 기 때문에 어떤 연산 이 먼저 진행 되 어야 하 는 지 를 제한 할 수 있 기 때문에 스 택 을 직접 이용 하여 계산 을 모 의 할 수 있 습 니 다.조작 수 를 만 나 직접 스 택 을 누 르 고 조작 자 를 만 나 스 택 꼭대기 의 2 개의 조작 수 를 직접 계산 한 다음 에 계산 결 과 를 스 택 에 누 르 면 이렇게 순환 합 니 다.마지막 스 택 에 남 은 유일한 요 소 는 전체 표현 식 의 값
  • 입 니 다.
  • 실현:
  • class Solution {
    public:
        int evalRPN(vector<string> &tokens) {
        	
        	int result = 0;
        	int i;
        	stack<int> opd;         //     
    		int size = tokens.size();
    		for(i=0;i<size;i++)
    		{
    			if(tokens[i]=="*")
    			{
    				int rOpd = opd.top();   //     
    				opd.pop();
    				int lOpd = opd.top();  //     
    				opd.pop();
    				result = lOpd*rOpd;
    				opd.push(result);
    			}
    			else if(tokens[i]=="/")
    			{
    				int rOpd = opd.top();
    				opd.pop();
    				int lOpd = opd.top();
    				opd.pop();
    				result = lOpd/rOpd;
    				opd.push(result);
    			}
    			else if(tokens[i]=="+")
    			{
    				int rOpd = opd.top();
    				opd.pop();
    				int lOpd = opd.top();
    				opd.pop();
    				result = lOpd+rOpd;
    				opd.push(result);
    			}
    			else if(tokens[i]=="-")
    			{
    				int rOpd = opd.top();
    				opd.pop();
    				int lOpd = opd.top();
    				opd.pop();
    				result = lOpd-rOpd;
    				opd.push(result);
    			}
    			else
    			{
    				opd.push(atoi(tokens[i].c_str()));
    			}
    		}
    		return opd.top();
        }
    };
    

    좋은 웹페이지 즐겨찾기