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

Basic Calculator II

时间:2015-10-31 10:13:49      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

 

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

 

以 3 + 2 * 2为例,这道题的重点是在循环到发现当前字符是*时,才对2进行处理 (push 2),然后更新sign。

public class Solution {
    public int calculate(String s) {
        s = s.replace(" ", "");
        int num = 0;
        char sign = ‘+‘;
        Stack<Integer> stack = new Stack<>();
        for(int i = 0; i < s.length(); ++i) {
            if(Character.isDigit(s.charAt(i))) {
                num = num * 10 + (s.charAt(i) - ‘0‘);
            }
            if(!Character.isDigit(s.charAt(i)) || i == s.length() - 1) {
                if(sign == ‘+‘) {
                    stack.push(num);
                } else if(sign == ‘-‘) {
                    stack.push(-num);
                } else if(sign == ‘*‘) {
                    stack.push(stack.pop() * num);
                } else if(sign == ‘/‘) {
                    stack.push(stack.pop() / num);;
                } 
                sign = s.charAt(i);
                num = 0;
            }
        }

        int res = 0;
        for(int ele: stack) {
            res += ele;
        }
        return res;
    }
}

 

Basic Calculator II

标签:

原文地址:http://www.cnblogs.com/Phoebe815/p/4925026.html

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