题目描述
无线基站接收到手机上报的某种信息(例如11@2$3@14)后,需要先进行解码操作,再计算结果。假定每条信息中都至少包含特殊运算符 @ 和 $ 的一种,解码规则如下:
x@y = 2*x+y+3
x$y = 3*x+2*y+1
- x、y 都是非负整数 ;
- @ 的优先级高于 $ ;
- 相同的特殊运算符,按从左到右的顺序计算。
现给定一个字符串,代表一个手机上报的待解码信息,请按照解码规则进行解码和计算,并返回计算结果。
解答要求
时间限制:1000ms, 内存限制:256MB
输入
一个字符串,表示一条手机上报的待解码信息,输入仅限数字字符和字符@$,长度范围 [3, 100]
用例保证输入的数字、计算过程以及结果的取值范围均为 [0, 2^31 - 1]
用例保证输入合法,@ $左右一定存在数字,且数字不存在前导0
不存在类似输入:@2$4,4$5@,4@$5
输出
一个整数,表示最终计算结果
样例
输入样例 1
11@2$3@14
输出样例 1
128
提示样例 1
计算过程
11@2$3@14
= (2*11+2+3)$3@14
= 27$3@14
= 27$(2*3+14+3)
= 27$23
= 3*27+2*23+1
= 128
因 @ 优先级高于 $,首先从左到右分别计算 11@2 和 3@14;再进行 $ 计算
11@2 套用公式 x@y = 2*x+y+3,结果为 27
输入样例 2
103$104@105@2$106@107
输出样例 2
5397
提示样例 2
其中 104@105@2 是连续的两个 @ 解码计算,按从左到右的顺序:首先计算 104@105,结果为 316; 再计算 316@2
Java算法源码
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class SignalDecoding {
// 分解递归
private static int getMatchResult(String information) {
if (information.contains("$")) {
String[] group$ = information.split("\\$");
int value = getMatchResult(group$[0]);
for (int i = 1; i < group$.length; i++) {
value = value * 3 + getMatchResult(group$[i]) * 2 + 1;
}
return value;
} else if (information.contains("@")) {
int value = getMatchResult(information.substring(0, information.lastIndexOf("@")));
value = 2 * value + Integer.parseInt(information.substring(information.lastIndexOf("@") + 1)) + 3;
return value;
} else {
return Integer.parseInt(information.trim());
}
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in, StandardCharsets.UTF_8.name());
String information = cin.nextLine().trim();
cin.close();
int result = getMatchResult(information);
System.out.println(result);
}
}