表达式求值

给定一个字符串描述的算术表达式,计算出结果值。 输入字符串长度不超过 100 ,合法的字符包括 ”+, -, *, , (, )” ,”0-9” 。

数据范围:运算过程中和最终结果均满足 ∣val∣≤2^31−1 ,即只进行整型运算,确保输入的表达式合法

输入描述:

输入算术表达式

输出描述:

计算出结果值

示例1

输入
400+5
输出
405

Java 编程

package cn.net.javapub.javaintroduction.example;

/**
 * @author: shiyuwang
 */

import java.io.IOException;
import java.io.InputStream;

public class Main {
    public static void main(String[] args) throws IOException {
        InputStream in = System.in;
        System.out.println(new ExprDemo().expr(in));
    }

    public static class ExprDemo {

        public char lastsign1 = 0, lastsign2 = 0;
        public int temp1 = 0, temp2 = 0;
        private static final char TEMPCHAR = 0;

        public int expr(InputStream in) throws IOException {
            int result = 0;
            char c;
            //循环遍历读取计算式中的所有字符
            a:
            while ((c = (char) in.read()) != '\n') {
                switch (c) {
                    case ')':
                    case ']':
                        //当遇到"}"时中断switch
                    case '}':
                        break a;
                    case '(':
                    case '[':
                        //当遇到"{"是
                    case '{':
                        temp2 = new ExprDemo().expr(in);
                        break;
                    case '+':
                    case '-':
                        jisuan1(TEMPCHAR);
                        result = jisuan2(c, result);
                        break;
                    case '*':
                    case '/':
                        jisuan1(c);
                        break;
                    default:
                        temp2 = temp2 * 10 + c - '0';
                        break;
                }
            }
            jisuan1(TEMPCHAR);
            result = jisuan2(TEMPCHAR, result);
            return result;
        }

        private void jisuan1(char c) {
            switch (lastsign2) {
                case 0:
                    temp1 = temp2;
                    break;
                case '*':
                    temp1 *= temp2;
                    break;
                case '/':
                    temp1 /= temp2;
                    break;
                default:
                    break;
            }
            temp2 = 0;
            lastsign2 = c;
        }

        private int jisuan2(char c, int result) {
            switch (lastsign1) {
                case 0:
                    result = temp1;
                    break;
                case '-':
                    result -= temp1;
                    break;
                case '+':
                    result += temp1;
                    break;
                default:
                    break;
            }
            temp1 = 0;
            lastsign1 = c;
            return result;
        }
    }

}

展示效果:

华为OD机试 - 表达式求值 (Java 2024 E卷 100分)_Java