递归实现基本计算器+-*/()

实现一个基本的计算器来计算一个简单的字符串表达式的值。

字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,乘号*,除号/,非负整数和空格 。

 1 /*
 2 
 3 https://leetcode-cn.com/problems/basic-calculator/
 4 
 5 实现一个基本的计算器来计算一个简单的字符串表达式的值。
 6 
 7 字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格  。
 8 
 9 扩展: * /
10 
11 * */
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.Stack;
15 
16 public class code224_CalculatorI
17 {
18     public int calculate(String s) {
19         List<Character> list = new ArrayList<>();
20         for(int i = 0; i < s.length(); i++)
21             list.add(s.charAt(i));
22         return helper(list);
23     }
24     public int helper(List<Character> s){
25         Stack<Integer> stack = new Stack<>();
26         char sign = '+';
27         int num = 0, res = 0;
28         while(s.size() > 0)
29         {
30             char c = s.remove(0);
31             if (Character.isDigit(c))
32             {
33                 num = 10 * num + (c - '0');
34             }
35             if (c == '(')
36                 num = helper(s);
37             if ((!Character.isDigit(c) && c != ' ') || s.size() == 0)
38             {
39                 if (sign == '+')
40                     stack.push(num);
41                 else if (sign == '-')
42                     stack.push(-num);
43                 else if (sign == '*')
44                 {
45                     stack.push(stack.pop() * num);
46                 }
47                 else if (sign == '/')
48                 {
49                     stack.push(stack.pop() / num);
50                 }
51                 sign = c;
52                 num = 0;
53             }
54             if (c == ')')
55             {
56                 break;
57             }
58         }
59         while (!stack.isEmpty()){
60             res += stack.pop();
61         }
62         return res;
63     }
64     public static void main(String[] args){
65         code224_CalculatorI calculator = new code224_CalculatorI();
66         System.out.println(calculator.calculate("2 * (3 + 5)"));
67         System.out.println(calculator.calculate("(1+(4+5+2)-3)+(6+8)"));
68     }
69 }
原文地址:https://www.cnblogs.com/Z-D-/p/12639502.html