Basic Calculator---Nice

来源:互联网 发布:windows 10桌面下载 编辑:程序博客网 时间:2024/06/18 12:51

题目描述

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

题目解答

解题思路

基本思路使用栈来解决,栈里面的内容是result和sign符号的正负
有很多细节需要注意

代码实现

public class Solution {    public int calculate(String s) {        if(s == null || s.length() == 0)            return -1;        // 栈里面保存结果 和 符号的正负        ArrayDeque<Integer> stack = new ArrayDeque<>();        //结果 符号 数值        int result = 0;        int sign = 1;        int num = 0;        for(int i = 0; i < s.length(); i++){            char c = s.charAt(i);            if(c >= '0' && c <= '9'){                //注意进位                num = num*10 +(c-'0');            }else if(c == '+'){                //遇到下一个 + - 再计算                result += (sign*num);                sign = 1;                num = 0;            }else if(c == '-'){                result += (sign*num);                sign = -1;                num = 0;            }else if(c == '('){                stack.push(result);                stack.push(sign);                result = 0;                sign = 1;            }else if(c == ')'){                //注意 括号里的结果                result += (sign*num);                result *= (stack.pop());                result += (stack.pop());                //括号里计算为完之后要清零                num = 0;            }        }        if(num != 0)            result += (sign*num);        return result;    }}
0 0
原创粉丝点击