Basic Calculator

来源:互联网 发布:怎么编写程序软件 编辑:程序博客网 时间:2024/04/28 11:10


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. 

关键点:stack

思路:遍历字符串,将字符串中的字符分成四类:

1) 数字0~9:采用类似字符串转整数的方法,得到操作数(operand = 10 * operand + c - '0')

2) 操作码“+”,“-”:操作数获取完成,此时可进行相应计算,并开始新一轮的计算

3) "(":标志着子字符串的开始,需要将父字符串的状态保存,即用stack保存之前的计算结果以及操作码

4) ")":标志着子字符串的结束,可将子字符串的结果加回父字符串。


代码:

public class Solution {    public int calculate(String s) {        if(s == null || s.length() == 0)return 0;        int result = 0, opr = 0;        int length = s.length();        Stack<Integer> stack = new Stack<>();        Map<Character, Integer> map = new HashMap<>();        map.put('+', 1);        map.put('-', -1);        // initial operator is '+'        char operator = '+';        for(int i = 0; i < length; i++) {        char c = s.charAt(i);        if(c == '(') {        stack.push(result);        stack.push(map.get(operator));        opr = 0;        result = 0;        operator = '+';        }        if(c == ')') {        result += map.get(operator)* opr;        // a is operator        int a = stack.pop();        // b is operand        int b = stack.pop();        result = b + a * result;        opr = 0;        }        if(c >= '0' && c <= '9') {        opr = 10 * opr + c - '0';        }        if(c == '+' || c == '-') {        result += map.get(operator) * opr;        operator = c;        opr = 0;        }        }        result += map.get(operator) * opr;        return result;    }}

 

0 0
原创粉丝点击