Basic Calculator II

来源:互联网 发布:淘宝网自动充值 编辑:程序博客网 时间:2024/05/23 00:03

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

思路:这题跟上题不一样的地方在于有了乘法和除法。这样的话,当前的数就要跟前面一个数发生关系,这样stack里面存的就是之前的数字,我们只要将乘法和除法计算完了push回stack,然后最后把所有的元素加起来就可以了。记住,如果是负数push进去是负数。sign代表的是之前遇到的符号位。首先得到当前的数,然后根据之前的符号再进行操作。

public class Solution {    public int calculate(String s) {        if(s == null || s.length() == 0) return 0;        int result = 0;          int num = 0;        int sign = '+';        Stack<Integer> stack = new Stack<Integer>();        for(int i=0; i<s.length(); i++){            char c = s.charAt(i);            if(isdigit(c)){                num = num*10 + c-'0';            }                        if(!isdigit(c) && c !=' ' || i==s.length()-1){                if(sign =='+'){                    stack.push(num);                } else if( sign == '-'){                    stack.push(-num);                } else if( sign == '*' || sign == '/'){                    int temp = sign == '*' ? stack.peek() * num : stack.peek() / num;                    stack.pop();                    stack.push(temp);                }                sign = c;                num = 0;            }        }                while(stack.size()>0){            result += stack.pop();        }        return result;    }        public boolean isdigit(char c){        return '0'<=c && c<='9';    }}


0 0
原创粉丝点击