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

224. Basic Calculator

时间:2017-07-14 13:30:56      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:space   pop   logs   function   min   括号   cti   sim   需要   

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

Note: Do not use the eval built-in library function.


 

一般是无法顺序执行、有些数据无法处理、需要回头再来处理时用到栈。在这个计算器中,如果只有‘+’,‘-‘运算,可以顺序执行。碰到(),需要把括号里整个表达式算出来,因此对()要用栈来处理。

对含有+ - * /的运算符,因为* /的优先级高于+ -,碰到了* /,前一个运算符若是+ 或者-,它需要延迟计算,因此对所有都要用到栈。

public class Solution {
    public int calculate(String s) {
        Stack<Integer> nums = new Stack<Integer>();
        Stack<Character> ops = new Stack<Character>();
        int re = 0, num = 0;
        char op = ‘+‘;
        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)) {
                case ‘+‘:
                case ‘-‘:
                    if (op == ‘+‘) {
                        re = re + num;
                    } else {
                        re = re - num;
                    }
                    num = 0;
                    op = s.charAt(i);
                    break;
                case ‘(‘:
                    nums.push(re);
                    ops.push(op);
                    re = 0;
                    op = ‘+‘;
                    break;
                case ‘)‘:
                    if (op == ‘+‘) {
                        re = re + num;
                    } else {
                        re = re - num;
                    }
                    num = 0;
                    char c = ops.pop();
                    int prev = nums.pop();
                    if (c == ‘+‘) {
                        re = prev + re;
                    } else {
                        re = prev - re;
                    }
                    break;
                case ‘ ‘:
                    break;
                default:
                    num = 10 * num + s.charAt(i) - ‘0‘;
            }
        }
        if (num != 0) {
            if (op == ‘+‘) {
                return re + num;
            } else {
                return re - num;
            }
        }
        return re;
    }
}

 

224. Basic Calculator

标签:space   pop   logs   function   min   括号   cti   sim   需要   

原文地址:http://www.cnblogs.com/yuchenkit/p/7169496.html

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