中级农民
- 积分
- 107
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-8-2
- 最后登录
- 1970-1-1
|
自己写的follow up 3,不一定完全对:
- public class Main {
- private static HashMap<Character, Integer> priority = new HashMap();
-
- public static void main(String[] args) {
- priority.put('+', 1); priority.put('-', 1);
- priority.put('*', 2); priority.put('/', 2);
- priority.put('^', 3);
- priority.put('=', 0);
- String expr = "3 + 5 * 4 ^ (2 - 1) * 10";
- System.out.println(calc(expr));
- }
-
- public static int calc(String expr) {
- Deque<Integer> vals = new ArrayDeque();
- Deque<Character> ops = new ArrayDeque();
- expr += "=";
- char[] array = expr.toCharArray();
- int num = 0;
- for (int idx = 0; idx < array.length; idx++) {
- char c = array[idx];
- if (c == ' ') continue;
- if (c == '(') {
- int start = idx;
- int cnt = 1;
- while (cnt != 0) {
- char tmp = array[++idx];
- if (tmp == '(') cnt++;
- if (tmp == ')') cnt--;
- }
- num = calc(expr.substring(start + 1, idx));
- }
- else if (Character.isDigit(c)) {
- num = num * 10 + (c - '0');
- }
- else {
- while (!ops.isEmpty() &&
- priority.get(ops.peek()) >= priority.get(c)) {
- char op = ops.pop();
- if (op == '+') {
- num += vals.pop();
- }
- else if (op == '-') {
- num = vals.pop() - num;
- }
- else if (op == '*') {
- num *= vals.pop();
- }
- else if (op == '/') {
- num = vals.pop() / num;
- }
- else if (op == '^') {
- num = (int) Math.pow(vals.pop(), num);
- }
- }
- vals.push(num);
- ops.push(c);
- num = 0;
- }
- }
- return vals.pop();
- }
- }
复制代码 |
|