您的位置:首页 > 编程语言 > Lua

【LeetCode】Evaluate Reverse Polish Notation(逆波兰表达式求值) -(Linkedin) Medium ++

2017-09-08 00:03 337 查看
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.

Example

[“2”, “1”, “+”, “3”, ““] -> ((2 + 1) 3) -> 9

[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6

【分析】

计算逆波兰表达式:

如第2例:凡不是运算符者——压栈,遇到运算符,如“/”,将从栈顶起2个元素弹栈,计算13/5 = 2,再将结果2压栈。又碰到“+”,将栈顶2个元素(2,4)弹出,计算2+4=6,再将6压栈。此时走到底了,最后,返回栈中唯一的栈顶元素6,即为运算结果。

注意!!!是 b/ab-a!!!!

(1)Java

import java.util.Stack;

public class Solution {
public static int ReversePolishNation(String[] tokens) {
Stack<Integer> s = new Stack<Integer>();
String operators = "+-*/";
for(String token : tokens){
if(!operators.contains(token)){//若非运算符,则压栈
s.push(Integer.valueOf(token));
continue;
}
int a = s.pop();
int b = s.pop();
if(token.equals("+") )
s.push(a+b);
else if(token.equals("-"))
s.push(b-a);
else if(token.equals("*"))
s.push(a*b);
else // if(token.equals("/"))
s.push(b/a);
}
return s.pop();
}
public static void main(String[] args){
String tokens[] = {"2", "1", "+", "3", "*"};
int answer = ReversePolishNation(tokens);
System.out.println(answer);
}
}


(2)C++

#include "stdafx.h"
#include <iostream>
#include <stack>

using namespace std;

bool IsOperator(const char* token) {
if (token[0] == '+' || token[0] == '-' || token[0] == '*' || token[0] == '/') {
return true;
}
return false;
}
int ReversePolishNation(const char* str[],int size) {
stack<int> s;
const char* token;
int a, b;
for (int i = 0; i < size; i++) {
token = str[i];
if (!IsOperator(token)) {//若不是运算符,则压入栈中
s.push(atoi(token));//atoi:array to integer
}
else {//若是运算符,则将栈中弹出2元素,将运算结果再压栈
a = s.top();
s.pop();
b = s.top();
s.pop();

if (token[0] == '+')
s.push(a + b);
else if (token[0] == '-')
s.push(b - a);
else if (token[0] == '*')
s.push(a * b);
else    // if (token[0] == '/')
s.push(b / a);

}
}

return s.top();
}

int main()
{
const char* str[] = {"2","1","+","3","*"};
int size = sizeof(str) / sizeof(const char*);//size的求值 不可以放在函数中!(见上一篇:数组指针)
cout << size << endl;
int value = ReversePolishNation(str, size);
cout << value << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: