码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-计算逆波兰表示法的值

时间:2014-07-29 12:29:36      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:style   blog   java   color   io   for   div   ar   

package edu.bupt.cici.leetcode;

import java.util.ArrayList;

public class EvaluateReversePolishNotation {

public int evalRPN(String[] tokens) {
int temp = 0;
int length = tokens.length;
ArrayList<Integer> stack = new ArrayList<Integer>();

for (int i = 0; i < length; i++) {
if (!tokens[i].matches("^[\\+\\-*/]$")) {
temp = Integer.parseInt(tokens[i]);
stack.add(Integer.parseInt(tokens[i]));
} else {
switch (tokens[i]) {
case "+":
temp = stack.get(stack.size() - 2)
+ stack.get(stack.size() - 1);
break;
case "-":
temp = stack.get(stack.size() - 2)
- stack.get(stack.size() - 1);
break;
case "*":
temp = stack.get(stack.size() - 2)
* stack.get(stack.size() - 1);
break;
case "/":
temp = stack.get(stack.size() - 2)
/ stack.get(stack.size() - 1);
break;

default:
break;
}
stack.remove(stack.size() - 1);
stack.remove(stack.size() - 1);
stack.add(temp);
}
}

return temp;

}

public static void main(String[] args) {
// TODO Auto-generated method stub
String[] ipt = { "-3","9","*" };
EvaluateReversePolishNotation eRPN = new EvaluateReversePolishNotation();
int opt = eRPN.evalRPN(ipt);
System.out.println(opt);

}

}

 

leetcode-计算逆波兰表示法的值,布布扣,bubuko.com

leetcode-计算逆波兰表示法的值

标签:style   blog   java   color   io   for   div   ar   

原文地址:http://www.cnblogs.com/bekitty/p/3874758.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!