首页 > 试题广场 >

简单表达式计算

[编程题]简单表达式计算
  • 热度指数:4419 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定一个合法的表达式字符串,其中只包含非负整数、加法、减法以及乘法符号(不会有括号),例如7+3*4*5+2+4-3-1,请写程序计算该表达式的结果并输出;


输入描述:
输入有多行,每行是一个表达式,输入以END作为结束


输出描述:
每行表达式的计算结果
示例1

输入

7+3*4*5+2+4-3-1
2-3*1
END

输出

69
-1

备注:
每个表达式的长度不超过10000,保证所有中间结果和最后结果在[-2e9,2e9]范围内
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static boolean isNumber(char ch) {
        return ch >= '0' && ch <= '9';
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str="";
        Stack<String> stack = new Stack<>();
        // 入栈
        str = in.nextLine();
        while(!str.equals("END")) {

            int i=0;
            while(i<str.length()) {
                // 如果当前是数字,则找全整个数,前一个为*则计算,否则直接入栈
                // 如果是+ - *直接入栈
                if(isNumber(str.charAt(i))) {
                    int left = i;
                    for(;i<str.length()&&isNumber(str.charAt(i));i++);
                    String num = str.substring(left, i);
                    // 前一个为非*,则直接入栈
                    if(stack.empty() || !stack.peek().equals("*"))
                        stack.add(num);
                        // 前一个为*,则计算后入栈
                    else {
                        stack.pop();
                        int x = Integer.valueOf(stack.pop()) * Integer.valueOf(num);
                        stack.add(x+"");
                    }
                } else {
                    stack.add(str.charAt(i)+"");
                    i++;
                }
            }

            // 转栈
            Stack<String> st = new Stack<>();
            while(!stack.empty()) st.add(stack.pop());

            // 出栈
            int num1 = Integer.valueOf(st.pop());
            while(!st.empty()) {
                String sign = st.pop();
                int num2 = Integer.valueOf(st.pop());
                if(sign.equals("+")) {
                    num1 += num2;
                } else num1 -= num2;
            }
            System.out.println(num1);
            str = in.nextLine();
        }


    }
}
发表于 2023-07-19 11:07:38 回复(0)
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = "";
        while (str.indexOf("END") == -1){
            str+= (br.readLine() + ",");
        }
        str = str.substring(0,str.indexOf("END")-1);
        String[] arr = str.split(",");
        for(int i=0;i<arr.length;i++){
            System.out.println(calcFunc(arr[i]));
        }
    }

    static int calcFunc(String ne){
        String operators = "+-*";
        char lastOperator = '+'; //上个运算符
        char tempOperator = ' '; //临时运算符
        int lastValue = 0; //上个值
        int previousVal = 0; //上上个值
        String currVal = "";
        char temp = ' ';
        int sum = 0;
        for(int i=0;i<ne.length();i++){
            temp = ne.charAt(i);
            if(operators.indexOf(temp) != -1){
                lastValue = lastOperator!='*'?Integer.valueOf(currVal):lastValue*Integer.valueOf(currVal);
                currVal = "";
                if(temp == '*'){
                    if(lastOperator == '*'){
                        lastOperator = temp;
                    }else{
                        tempOperator = lastOperator;
                        lastOperator=temp;
                    }
                }else{
                    if(lastOperator == '*'){
                        sum +=previousVal;
                        previousVal = Integer.valueOf(""+tempOperator+lastValue);
                        lastOperator = temp;
                    }else{
                        sum += previousVal;
                        previousVal = lastOperator == '+'? lastValue : Integer.valueOf(""+lastOperator+lastValue);
                        lastOperator = temp;
                    }
                }
            }else{
                currVal += temp;
                if(i == ne.length()-1){
                    if(lastOperator == '*'){
                        lastValue = lastValue * Integer.valueOf(currVal);
                        if(tempOperator == '-'){
                            sum += (previousVal - lastValue);
                        }else {
                            sum +=(previousVal + lastValue);
                        }
                    }else{
                        sum +=(previousVal + Integer.valueOf(""+lastOperator + currVal));
                    }
                }
            }
        }
        return sum;
    }
}

编辑于 2022-11-03 17:42:18 回复(0)
import java.util.*;

public class Main{
    
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String str = sc.next();
            if(!str.equals("END")){
                int res=0;
                int d=0;
                char sign='+';
                Stack<Integer> S = new Stack<>();
                for(int i=0;i<str.length();++i){
                    char c = str.charAt(i);
                    if(c>='0'){
                        d = d*10 -'0' + c;
                    }
                    if((c<'0')||i==str.length()-1){
                        if(sign=='+'){
                            S.push(d);
                        }
                        else if(sign=='-'){
                            S.push(-d);
                        }
                        else if(sign=='*'){
                            int tmp = S.peek()*d;
                            S.pop();
                            S.push(tmp);
                        }
                        d=0;
                        sign=c;
                    }
                }
                while(!S.isEmpty()){
                    res+=S.peek();
                    S.pop();
                }
                System.out.println(res);
            }
        }
       
    }
}

发表于 2020-08-24 15:42:24 回复(0)
整体思路:从前往后消除乘号
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * @Author: coderjjp
 * @Date: 2020-05-07 18:36
 * @Description:
 * @version: 1.0
 */
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String cur;
        while (!(cur=br.readLine()).equals("END")){
            String s1[] = cur.split("[+\\-*]");//
            ArrayList<Integer> nums = new ArrayList<>();//保存数字
            for (int i = 0; i < s1.length; i++)
                nums.add(Integer.valueOf(s1[i]));
            StringBuilder ch = new StringBuilder()//保存符号
                    .append(cur.replaceAll("\\d",""));
            int i = 0;
            while (i < ch.length()){
                if (ch.charAt(i) == '*'){//核心代码,只有4行
                    nums.set(i, nums.get(i)*nums.get(i+1));
                    nums.remove(i+1);
                    ch.deleteCharAt(i);
                    continue;
                }
                i++;
            }
                        /*至此只有+-,从前向后计算即可*/
            if (nums.size()==1)
                System.out.println(nums.get(0));
            else {
                int res = addOrSub(nums.get(0), nums.get(1), ch.charAt(0));
                for (i = 1; i < ch.length(); i++)
                    res = addOrSub(res, nums.get(i+1),ch.charAt(i));
                System.out.println(res);
            }
        }
    }
    private static int addOrSub(int num1, int num2, char c){
        if (c == '+')
            return num1 + num2;
        else
            return num1 - num2;
    }
}


整体思路,先计算*/,再计算+-,但是这段AC代码不想再看第二遍,逻辑太混乱🤣
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * @Author: coderjjp
 * @Date: 2020-05-07 16:02
 * @Description:
 * @version: 1.0
 */
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String cur;
        while (!(cur=br.readLine()).equals("END")){
            String s1[] = cur.split("[+\\-*/]");
            int nums[] = new int[s1.length];
            for (int i = 0; i < s1.length; i++)
                nums[i] = Integer.valueOf(s1[i]);
            String s2 = cur.replaceAll("\\d","");
            char[] chs = new char[s2.length()];
            for (int i = 0; i < chs.length; i++)
                chs[i] = s2.charAt(i);
            ArrayList<Integer> n = new ArrayList<>();
            ArrayList<Character> c = new ArrayList<>();
            for (int i = 0; i < chs.length; i++ ){
                if (chs[i] == '+' || chs[i] == '-'){
                    n.add(nums[i]);
                    c.add(chs[i]);
                }else {
                    int temp = mulOrDiv(nums[i], nums[i+1],chs[i]);
                    for (i = i + 1; i < chs.length && (chs[i] == '*' || chs[i] == '/');i++){
                        temp = mulOrDiv(temp, nums[i+1],chs[i]);
                    }
                    n.add(temp);
                    if (i < chs.length)
                        c.add(chs[i]);
                }
            }
            if (n.size() == c.size()) n.add(nums[nums.length-1]);
            if (n.size()==1){
                System.out.println(n.get(0));
                continue;
            }
            int res = addOrSub(n.get(0), n.get(1), c.get(0));
            for (int i = 1; i < c.size(); i++ )
                res = addOrSub(res, n.get(i+1), c.get(i));
            System.out.println(res);
        }
    }

    private static int mulOrDiv(int num1, int num2, char c){
        if (c == '*')
            return num1 * num2;
        else
            return num1 / num2;
    }

    private static int addOrSub(int num1, int num2, char c){
        if (c == '+')
            return num1 + num2;
        else
            return num1 - num2;
    }
}


编辑于 2020-05-07 19:01:38 回复(0)

热门推荐

通过挑战的用户

查看代码