[关闭]
@yexiaoqi 2022-05-20T08:39:47.000000Z 字数 1610 阅读 332

HJ54. 表达式求值

刷题


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

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

输入描述:输入算术表达式
输出描述:计算出结果值

示例

输入:400+5
输出:405

类似的题目还有 HJ50. 四则运算

  1. import java.util.*;
  2. import javax.script.*;
  3. public class Main {
  4. public static void main(String[] args) throws ScriptException {
  5. Scanner sc = new Scanner(System.in);
  6. while(sc.hasNext()){
  7. String s = sc.nextLine()
  8. .replace("[","(")
  9. .replace("]",")")
  10. .replace("{","(")
  11. .replace("}",")");
  12. System.out.println(eval1(s));
  13. System.out.println(eval2(s));
  14. }
  15. }
  16. //方法一
  17. public static int eval1(String s) {
  18. char ops = '+';
  19. Stack<Integer> stack = new Stack<>();
  20. for(int i=0; i<s.length(); i++){
  21. char c = s.charAt(i);
  22. if(c == ' ') continue;
  23. if(Character.isDigit(c)){
  24. int num = 0;
  25. while(i<s.length() && Character.isDigit(s.charAt(i))){
  26. num = num*10 + s.charAt(i) - '0';
  27. i++;
  28. }
  29. i--;
  30. if(ops == '+') stack.push(num);
  31. else if(ops == '-') stack.push(-num);
  32. else if(ops == '*') stack.push(stack.pop()*num);
  33. else if(ops == '/') stack.push(stack.pop()/num);
  34. } else if (c=='+' || c=='-' || c=='*' || c=='/'){
  35. ops = c;
  36. } else if (c == '('){
  37. int left = i;//左括号当前位置的索引
  38. int right = i+1;
  39. int count = 1;//括号层级计数
  40. while(right<s.length() && count>0){
  41. if(s.charAt(right)=='(') count++;
  42. else if(s.charAt(right)==')') count--;
  43. right++;
  44. }
  45. i = right-1;
  46. //取()里面的表达式继续计算
  47. int num = eval1(s.substring(left+1, right-1));
  48. if(ops == '+') stack.push(num);
  49. else if (ops == '-') stack.push(-num);
  50. else if (ops == '*') stack.push(stack.pop()*num);
  51. else if (ops == '/') stack.push(stack.pop()/num);
  52. }
  53. }
  54. int ans = 0;
  55. while(!stack.isEmpty()) ans+=stack.pop();
  56. return ans;
  57. }
  58. //方法二:使用java8自带的js引擎,但有时并不满足时间和内存限制
  59. public static int eval2(String s) throws ScriptException {
  60. ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn");
  61. return scriptEngine.eval(s);
  62. }
  63. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注