华为试机题:表达式求值

题目:

例子:

分析:

(1)如果有括号先计算括号里面的。

(2)通过栈Stack来实现计算,如果是乘除,先将栈里面的数字出栈计算,然后再入栈。

 public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            while (scan.hasNext()) {
                String s = scan.nextLine();
                System.out.println(solution(s));
            }
        }
        public  static int solution(String s) {
            //括号用递归处理
            char ops = '+';
            Stack<Integer> stack = new Stack<>();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c == ' ') continue;
                //Character.isDigit(c)判断字符是否是数字
                if (Character.isDigit(c)) {
                    int num = 0;
                    //将数字字符转换为整数
                    while (i < s.length() && Character.isDigit(s.charAt(i))) {
                        num = num * 10 + s.charAt(i) - '0';
                        i++;
                    }
                    i--;
                    if (ops == '+') stack.push(num);
                    else if (ops == '-') stack.push(-num);
                    else if (ops == '*') stack.push(stack.pop() * num);
                    else if (ops == '/') stack.push(stack.pop() / num);
                }
                else if (c == '+' || c == '-' || c == '*' || c == '/') {
                    ops = c;
                }
                else if (c == '(') {
                    int left = i;
                    int right = i + 1;
                    int count = 1;
                    while (right < s.length() && count > 0) {
                        if (s.charAt(right) == '(') count++;
                        else if (s.charAt(right) == ')') count--;
                        right++;
                    }
                    i = right - 1;
                    int num = solution(s.substring(left + 1, right - 1));
                    if (ops == '+') stack.push(num);
                    else if (ops == '-') stack.push(-num);
                    else if (ops == '*') stack.push(stack.pop() * num);
                    else if (ops == '/') stack.push(stack.pop() / num);
                }
            }
            int res = 0;
            while (!stack.isEmpty()) res += stack.pop();
            return res;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值