一、题目
给定包含特殊运算符号@,$ ,转换规则如下
x@y=2x+y+3
x$y =3x+2y+1
其中x,y都是非负整数且@优先级高于 $。
相同的特殊运算符,从左到右顺序计算。用例保证@,$,左右一定存在数字,且数字不存在前导为0。
输入
11@2$3@14
结果
128
二、算法实现
方法1
public static int getMatchResult(String information) {
Queue<Integer> queue = new LinkedList<>();
// 从$切分,注意转义
String[] info = information.split("\\$");
for (String s : info) {
if (s.contains("@")) {
String[] split = s.split("@");
int n1 = Integer.parseInt(split[0]);
int simple = 0;
for (int i = 1; i < split.length; i++) {
simple = 2 * n1 + Integer.parseInt(split[i]) + 3;
n1 = simple;
}
queue.add(simple);
} else {
queue.add(Integer.valueOf(s));
}
}
if (queue.size() == 1) {
return queue.peek();
}
int count = 0;
// 获取并移除队首元素
int temp = queue.poll();
while (!queue.isEmpty()) {
count = 3 * temp + 2 * queue.poll() + 1;
temp = count;
}
return count;
}
方法2
在这里插入代码片