1、题目描述
LISP 语言唯一的语法就是括号要配对。
形如 (OP P1 P2 …),括号内元素由单个空格分割。
其中第一个元素 OP 为操作符,后续元素均为其参数,参数个数取决于操作符类型。
注意:
参数 P1, P2 也有可能是另外一个嵌套的 (OP P1 P2 …) ,当前 OP 类型为 add / sub / mul / div(全小写),分别代表整数的加减乘除法,简单起见,所有 OP 参数个数均为 2 。
举例:
● 输入:(mul 3 -7)输出:-21
● 输入:(add 1 2) 输出:3
● 输入:(sub (mul 2 4) (div 9 3)) 输出 :5
● 输入:(div 1 0) 输出:error
题目涉及数字均为整数,可能为负;
不考虑 32 位溢出翻转,计算过程中也不会发生 32 位溢出翻转,
除零错误时,输出 “error”,
除法遇除不尽,向下取整,即 3/2 = 1
2、输入描述
输入为长度不超过512的字符串,用例保证了无语法错误。
3、输出描述
输出计算结果或者“error”。
温馨提示!!!
华为OD机试考试官方会对考生代码查重。华为od机试因为有题库所以有很大的概率抽到原题。如果碰到了题库中的原题,千万不要直接使用题解中的代码,一定要做些修改,比如代码中的变量名,除此之外,代码的组织结构和逻辑也要进行一些改变,所以在日常的刷题中,要提前编写好属于自己的代码。
4、题解
定义两个栈,一个存数字,一个存操作符,如果是‘(’,则操作符入栈,否则数字入栈,如果是‘)’,弹出num2、弹出num1,弹出操作符进行运算
代码如下:
// 数字
private static Stack<Integer> numStack = new Stack<>();
// 操作符
private static Stack<String> opStack = new Stack<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int index = 0;
int num1;
int num2;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == '(') {
// 操作符入栈
opStack.push(str.substring(i + 1, i + 4));
i += 4;
index = i + 1;
} else if (ch == ')') {
// 计算标识符
if (index < i) {
// 数字入栈
numStack.push(Integer.parseInt(str.substring(index, i)));
i += 1;
index = i + 1;
}
num2 = numStack.pop();
num1 = numStack.pop();
// 计算
calc(num1, num2);
} else {
if (ch == ' ') {
if (index < i) {
// 数字入栈
numStack.push(Integer.parseInt(str.substring(index, i)));
index = i + 1;
}
}
}
}
while (opStack.size() != 0) {
num2 = numStack.pop();
num1 = numStack.pop();
calc(num1, num2);
}
System.out.println(numStack.get(0));
}
public static void calc(int num1, int num2) {
String op = opStack.pop();
switch (op) {
case "add":
numStack.push(num1 + num2);
break;
case "sub":
numStack.push(num1 - num2);
break;
case "mul":
numStack.push(num1 * num2);
break;
case "div":
if (num2 == 0) {
System.out.println("error");
System.exit(0);
} else {
int result = num1 / num2;
if (num1 % num2 != 0) {
// 处理正负数
if (result < 0) {
result -= 1;
} else {
result += 1;
}
}
numStack.push(result);
}
break;
default:
System.out.println("error");
break;
}
}
执行结果如下: