150. Evaluate Reverse Polish Notation

You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.

Evaluate the expression. Return an integer that represents the value of the expression.

Note that:

  • The valid operators are '+', '-', '*', and '/'.
  • Each operand may be an integer or another expression.
  • The division between two integers always truncates toward zero.
  • There will not be any division by zero.
  • The input represents a valid arithmetic expression in a reverse polish notation.
  • The answer and all the intermediate calculations can be represented in a 32-bit integer.

 

Example 1:

Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

 

Constraints:

  • 1 <= tokens.length <= 104
  • tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].

SOL:

這一題的解題思路不難,將tokens依序放入stack中,若遇到數字則放入stack,若遇到運算符號 '+', '-', '*', and '/',則取出stack中的兩個數字進行運算之後再放入stack。

stack的用處相對單純,所以用 array+top 即可實作出來。

但在過程中比較困擾我的是字元比較以及字串比較

一開始的想說可以單純地用字元判斷:

if(tokens[i]=='+')

但因為 char ** tokens 所以 tokens[i] 其實會是一個 char * 而不僅只是一個 char,所以當然沒辦法使用字元比較。

值得注意的是,使用這個寫法程式不會報錯,但不會進到這個 if 判斷式中。

除了可以問 chatgpt 答案之外,也可以問字元比較以及字串比較,不用自己估狗真的好方便。

image

image

 

#define MAX_SIZE 10000

int evalRPN(char ** tokens, int tokensSize){
    int stack[MAX_SIZE];
    int top = -1;
    int num1, num2;
    for(int i = 0; i<tokensSize; i++){
        if(strcmp(tokens[i], "+")==0){
            num1 = stack[top--];
            num2 = stack[top--];
            stack[++top]=num2+num1;
        }
        else if(strcmp(tokens[i], "-")==0){
            num1 = stack[top--];
            num2 = stack[top--];
            stack[++top]=num2-num1;
        }
        else if(strcmp(tokens[i], "*")==0){
            num1 = stack[top--];
            num2 = stack[top--];
            stack[++top]=num2*num1;
        }
        else if(strcmp(tokens[i], "/")==0){
            num1 = stack[top--];
            num2 = stack[top--];
            stack[++top]=num2/num1;
        }
        else
            stack[++top]=atoi(tokens[i]);

    }
    return stack[top];
}

 

順便附上型態轉換的說明。

image

image

arrow
arrow
    創作者介紹
    創作者 yoruru 的頭像
    yoruru

    yoruru的努力日記

    yoruru 發表在 痞客邦 留言(0) 人氣()