给定一个字符串描述的算术表达式,计算出结果值。
输入字符串长度不超过 100 ,合法的字符包括 ”+, -, *, /, (, )” , ”0-9” 。
数据范围:运算过程中和最终结果均满足 ,即只进行整型运算,确保输入的表达式合法
import java.util.*; import javax.script.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) throws Exception { Scanner scan = new Scanner(System.in); String input = scan.nextLine(); ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn"); System.out.println(scriptEngine.eval(input)); } }
给定一个字符串描述的算术表达式,计算出结果值。
输入算术表达式
计算出结果值
400+5复制
405
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { /** 无视左括号 将操作数压入操作数栈 将运算符压入运算符栈 在遇到右括号的时候,从运算符栈中弹出一个运算符,再从操作数栈中弹出所需的操作数, 并且将运算结果压入操作数栈中 */ public static void main(String[] args) { Scanner in = new Scanner(System.in); Stack<Integer> s1 = new Stack<>(); //操作数栈 Stack<Character> s2 = new Stack<>(); //运算符栈 // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String str = in.nextLine(); int len = str.length(); String tem = ""; for(int i=0; i<len; i++) { char ch = str.charAt(i); switch(ch) { case '(': case '[': case '{': break; //忽略 case '+': case '-': case '*': case '/': s2.push(ch);//操作符入栈 break; case ')': case ']': case '}': //计算,并将操作数重新入栈 //1.弹出操作符 //2.弹出操作数1 //3.弹出操作数2 //计算,并将结果重新放到操作数栈 char flag = s2.pop(); Integer num1 = s1.pop(); Integer num2 = s1.pop(); Integer sum = null; switch(flag) { case '+': sum = num1 + num2; s1.push(sum); break; case '-': sum = num1 - num2; s1.push(sum); break; case '*': sum = num1 * num2; s1.push(sum); break; case '/': sum = num1 / num2; s1.push(sum); break; } break; default: tem += String.valueOf(ch); if(!nextIsNotNum(str, i, len)) { s1.push(Integer.parseInt(tem)); tem = ""; } break; } } //统计并输出 int res = 0; while(!s1.isEmpty()) { res += s1.pop(); } System.out.println(res); } } public static boolean nextIsNotNum(String str, int n, int len) { int temp = -1; try { temp = Integer.parseInt(String.valueOf(str.charAt(n+1))); } catch(Exception e) { temp = -1; } return temp != -1; } }
package com.ihang.learn.java.huawei; import java.util.Deque; import java.util.LinkedList; import java.util.Scanner; import java.util.Stack; /** * @author yaohangyang * @date 2022/11/7 */ public class HJ54 { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case System.out.println(hj54(in.nextLine())); } } //中缀表达式转后缀表达式 public static Deque<String> Mid2End(String str) { //用于存运算数 StringBuilder number = new StringBuilder(); //后缀表达式 Deque<String> deque = new LinkedList<>(); //运算操作符 Stack<Character> stack = new Stack<>(); boolean flag = false; for(int i = 0; i<str.length(); i++){ char c = str.charAt(i); if(c>='0' && c<='9'){ number.append(c); }else { if(number.length()>0){ if(flag){ deque.add("-"+number.toString()); flag = false; }else { deque.add(number.toString()); } number.delete(0,number.length()); } if(c=='('){ stack.push(c); }else if(c==')'){ char top = stack.peek(); while (top!='('){ deque.add(stack.pop()+""); top = stack.peek(); } stack.pop(); }else if(c=='-' && (i==0 || str.charAt(i-1)=='(')){ // 用于处理运算数是负数的情况 比如:-1*(-1-1) => -1 -1 1 - * flag = true; }else { if(stack.size()<=0 || stack.peek()=='(' || opeCompare(c,stack.peek())){ stack.push(c); }else { while (stack.size()>0 && stack.peek()!='(' && !opeCompare(c,stack.peek())){ deque.add(stack.pop()+""); } stack.push(c); } } } } if(number.length()>0){ deque.add(number.toString()); } while (stack.size()>0){ deque.add(stack.pop()+""); } return deque; } //运算符优先级比较 public static boolean opeCompare(char a ,char b){ if(a=='*' || a=='/'){ if(b=='+' || b=='-'){ return true; } } return false; } //后缀表达式计算 public static int hj54(String str){ Deque<String> deque = Mid2End(str); Stack<Integer> stack = new Stack<>(); while (deque.size()>0){ String s = deque.pollFirst(); if(s.charAt(s.length()-1)>='0' && s.charAt(s.length()-1)<='9'){ stack.push(Integer.parseInt(s)); }else { int b = stack.pop(); int a = stack.pop(); int r = 0; switch (s.charAt(0)){ case '*': r = a*b; break; case '/': r = a/b; break; case '+': r = a+b; break; case '-': r = a-b; break; default: break; } stack.push(r); } } return stack.pop(); } }
import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedReader; import java.util.Stack; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); System.out.println(calculate(line)); } public static int calculate(String line){ Stack<Integer> stack = new Stack<>(); char sign = '+'; int number = 0; int len = line.length(); char[] chars = line.toCharArray(); for(int i = 0; i < len; i++){ char ch = chars[i]; if(ch == ' ')continue; if(Character.isDigit(ch)){ number = number * 10 + ch - '0'; } if(ch == '('){ int count = 1; int j = i + 1; while(count > 0){ if(chars[j] == ')')count--; if(chars[j] == '(')count++; j++; } //递归,解小括号中的表达式 number = calculate(line.substring(i + 1, j - 1)); i = j - 1; } if(!Character.isDigit(ch) || i == len - 1){ if(sign == '+'){ stack.push(number); }else if(sign == '-'){ stack.push(-1 *number); }else if(sign =='*'){ stack.push(stack.pop() * number); }else if(sign == '/'){ stack.push(stack.pop() / number); } //更新符号 sign = ch; //刷新数字 number = 0; } } //栈中数字求和得到结果 int ans = 0; while (!stack.isEmpty()) { ans += stack.pop(); } return ans; } }
import java.io.IOException; import java.io.InputStream; import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) throws IOException { InputStream in = System.in; Scanner scanner = new Scanner(in); String str = scanner.nextLine(); int result = getEvaluation(str); System.out.println(result); } private static int getEvaluation(String str) { if (str == null || str.length() == 0) return 0; // 记录数值 Stack<Integer> arithmetic = new Stack<>(); // 记录运算符 Stack<Character> operator = new Stack<>(); int i = 0; while(i < str.length()) { // 对负数的判断 boolean negative = false; if ((str.charAt(i) == '-' && arithmetic.isEmpty()) || (str.charAt(i) == '-' && !(str.charAt(i-1) >= '0' && str.charAt(i-1) <= '9') && str.charAt(i-1) != ')')) { negative = true; i++; } // 保存数值 if (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'){ StringBuilder builder = new StringBuilder(); while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'){ builder.append(str.charAt(i)); i++; } arithmetic.push(negative ? -Integer.valueOf(builder.toString()) : Integer.valueOf(builder.toString())); } // 出栈处理数值 if (i < str.length() && (str.charAt(i) == '+' || str.charAt(i) == '-')) { while (!operator.isEmpty() && (operator.peek() == '*' || operator.peek() == '/')) { Character op = operator.pop(); Integer n1 = arithmetic.pop(); Integer n2 = arithmetic.pop(); arithmetic.push(operation(n2, n1, op)); } while (!operator.isEmpty() && (operator.peek() == '+' || operator.peek() == '-')){ Character op = operator.pop(); Integer n1 = arithmetic.pop(); Integer n2 = arithmetic.pop(); arithmetic.push(operation(n2, n1, op)); } operator.push(str.charAt(i)); i++; } // 遇到右括号再出栈处理 else if (i < str.length() && (str.charAt(i) == ')')){ while (true){ Character op = operator.pop(); if (op == '(') break; Integer n1 = arithmetic.pop(); Integer n2 = arithmetic.pop(); arithmetic.push(operation(n2,n1,op)); } i++; } // 其他情况运算符入栈即可 else{ if (i == str.length()) break; operator.push(str.charAt(i)); i++; } } while (!operator.isEmpty()){ Character op = operator.pop(); Integer n1 = arithmetic.pop(); Integer n2 = arithmetic.pop(); arithmetic.push(operation(n2,n1,op)); } return arithmetic.pop(); } /** * 基础运算 */ private static Integer operation(Integer n1, Integer n2, Character op) { if (op == '+') return n1 + n2; else if (op == '-') return n1 - n2; else if (op == '*') return n1 * n2; else return n1 / n2; } }
import java.util.*; public class Main { static int index = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String input = sc.next(); int res = calculate(input); System.out.println(res); } public static int calculate(String s) { Deque<Integer> stack = new LinkedList<>(); int length = s.length(); char prevSign = '+'; while (index < length) { char c = s.charAt(index); if (c == '(') { index++; int num = calculate(s); // 遇到左括号时,递归调用获取括号内表达式的值 calculateCurData(stack, prevSign, num); // 根据括号前面的一个运算符处理括号内表达式的计算结果 if (index < length) prevSign = s.charAt(index++); // 求出右括号后面紧跟的符号 } else if (prevSign == ')') { break; } else { // 求不包含括号时的表达式的值 int num = 0; while (index < length && Character.isDigit(s.charAt(index))) { num = num * 10 + s.charAt(index) - '0'; index++; } calculateCurData(stack, prevSign, num); if (index == length) break; prevSign = s.charAt(index++); } } return calculateRes(stack); } private static void calculateCurData(Deque<Integer> stack, char prevSign, int num) { if (prevSign == '+') { stack.push(num); } else if (prevSign == '-') { stack.push(-num); } else if (prevSign == '*') { stack.push(stack.pop() * num); } else if (prevSign == '/') { stack.push(stack.pop() / num); } } private static int calculateRes(Deque<Integer> stack) { int res = 0; while (!stack.isEmpty()) { res += stack.pop(); } return res; } }
import java.util.HashMap; import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); char[] charArray = (sc.next() + "#").toCharArray(); Stack<Character> signStack = new Stack<>(); Stack<Integer> numStack = new Stack<>(); HashMap<Character, Integer> map = new HashMap<>(); map.put('+', 0); map.put('-', 1); map.put('*', 2); map.put('/', 3); map.put('(', 4); map.put(')', 5); map.put('#', 6); char[][] chars = new char[][]{ {'>', '>', '<', '<', '<', '>', '>'}, {'>', '>', '<', '<', '<', '>', '>'}, {'>', '>', '>', '>', '<', '>', '>'}, {'>', '>', '>', '>', '<', '>', '>'}, {'<', '<', '<', '<', '<', '=', 'e'}, {'e', 'e', 'e', 'e', 'e', 'e', 'e'}, {'<', '<', '<', '<', '<', 'e', '='}, }; signStack.push('#'); int i = 0; while (i < charArray.length) { int sign = 1; if ((i == 0 || charArray[i - 1] == '(') && charArray[i] == '-') { i++; sign = -1; } if (isNum(charArray[i])) { int sum = 0; while (isNum(charArray[i])) { sum *= 10; sum += charArray[i] - '0'; i++; } numStack.push(sign * sum); } else { switch (chars[map.get(signStack.peek())][map.get(charArray[i])]) { case '<': signStack.push(charArray[i++]); break; case '>': Integer rightVal = numStack.pop(); Integer leftVal = numStack.pop(); Character ops = signStack.pop(); numStack.push(operate(leftVal, rightVal, ops)); break; case '=': signStack.pop(); i++; break; default: throw new RuntimeException("error"); } } } if (signStack.isEmpty() && numStack.size() == 1) System.out.println(numStack.peek()); } private static Integer operate(Integer leftVal, Integer rightVal, Character ops) { switch (ops) { case '+': return leftVal + rightVal; case '-': return leftVal - rightVal; case '*': return leftVal * rightVal; case '/': return leftVal / rightVal; default: return null; } } private static boolean isNum(char c) { return c >= '0' && c <= '9'; } }
// 提交一个笨方法 public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); while (str.contains(")")) { int start = 0; // 发现反括号往前搜索最近的一个括号,先解析本组数据 int end = str.indexOf(")"); for (int i = end; i >= 0; i--) { if ('(' == str.charAt(i)) { start = i; break; } } String tmp = str.substring(start, end + 1); // System.out.println("获取括号 tmp=" + tmp); int n = getResult(str.substring(start + 1, end)); str = str.replace(tmp, String.valueOf(n)); } System.out.println(getResult(str) + ""); } private static int getResult(String str) { // 运算乘法 while (str.contains("*")) { int pre = getPreNum(str, "*", "\\d+"); int next = getNextNum(str, "*"); str = str.replace(pre+"*"+next, String.valueOf(pre*next)); // System.out.println("运算* str=" + str); } // 运算除法 while (str.contains("/")) { int pre = getPreNum(str, "*/", "\\d+"); int next = getNextNum(str, "/"); str = str.replace(pre+"/"+next, String.valueOf(pre/next)); // System.out.println("运算/ str=" + str); } str = str.replace("+-", "-"); str = str.replace("--", "+"); if (str.startsWith("+")) { str = str.substring(1); } // 运算加法 while (str.contains("+")) { str = str.replaceAll("\\+0|\\-0", ""); int pre = getPreNum(str, "+", "\\-*\\d+"); // 加减法运算符前面的数把符号也算上 int next = getNextNum(str, "+"); // System.out.println("运算+ pre=" + pre + ",next=" + next); str = str.replace(pre+"+"+next, pre < 0? "+" + String.valueOf(pre+next) : String.valueOf(pre+next)); } str = str.replace("+-", "-"); str = str.replace("--", "+"); if (str.startsWith("+")) { str = str.substring(1); } // 运算减法 while (str.substring(1).contains("-")) { str = str.replaceAll("\\+0|\\-0", ""); if (str.startsWith("-")) { str = str.substring(1); int pre = getPreNum(str, "-", "\\-*\\d+"); // 加减法运算符前面的数把符号也算上 int next = getNextNum(str, "-"); str = "-" + str.replace(pre+"-"+next, String.valueOf(pre+next)); } else { int pre = getPreNum(str, "-", "\\-*\\d+"); // 加减法运算符前面的数把符号也算上 int next = getNextNum(str, "-"); str = str.replace(pre+"-"+next, String.valueOf(pre-next)); } // System.out.println("运算- str=" + str); } return str.startsWith("-") ? -Integer.parseInt(str.substring(1)) : Integer.parseInt(str); } // 获取运算符前面的数 private static int getPreNum(String str, String fuhao, String relgex) { int n = str.indexOf(fuhao); String result = ""; String tmp = result; while (true && n > 0) { tmp = String.valueOf(str.charAt((n - 1))) + tmp; if (!tmp.matches(relgex)) { break; } result = tmp; // System.out.println("前面数=" + tmp); --n; } return result == ""? 0: (result.contains("-")? -Integer.parseInt(result.substring(1)): Integer.parseInt(result)); } // 获取运算符后面的数 private static int getNextNum(String str, String fuhao) { int n = str.indexOf(fuhao); String result = ""; String tmp = result; while (true && n < str.length() - 1) { tmp = tmp + String.valueOf(str.charAt((n + 1))); if (!tmp.matches("\\-|\\-*\\d+")) { break; } result = tmp; // System.out.println("后面数=" + tmp); ++n; } return result == "" ? 0: (result.startsWith("-") ? -Integer.parseInt(result.substring(1)): Integer.parseInt(result)); }