火星文算法
假设有一种不同于四则运算的算法符号或新闻
其中
x#y表示2x+3y+4
x$y表示3*x+y+2
其中$的有限级高于#(类似于乘除法高于加减法)同时遵循从左往右的计算规则。请写出对应算法正确计算出火星文的最终结果
以下用例
123#4$5#67$78#123#4$5#67$78
输出结果
14149
package xzc.huawei.partise02;
import java.util.Scanner;
public class test01 {
public static void main(String[] args) {
//123#4$5#67$78
Scanner in = new Scanner(System.in);
String next = in.nextLine();
String parseRule01 = parseRule01(next);
String parseRule02 = parseRule02(parseRule01);
System.out.println(parseRule02);
}
//123#4$5#67$78#123#4$5#67$78
//1.循环算$ 将$清零
static String parseRule01(String str){
int RowLength = str.length();
int endIndex = 0;
String[] rowStr = str.split("\\$");
// int opNumber = rowStr.length - 1;
// System.out.println("opNumber "+opNumber);
// System.out.println("str "+str);
String substring = new String();
if (rowStr.length>2){
endIndex =rowStr[0].length() + rowStr[1].length()+1;
substring = str.substring(endIndex, RowLength);
}
if (rowStr.length>1){
String[] leftNumberStr = rowStr[0].split("#");
int leftNumber = Integer.parseInt(leftNumberStr[leftNumberStr.length-1]);
int subLength = leftNumberStr[leftNumberStr.length - 1].length();
rowStr[0] = rowStr[0].substring(0, rowStr[0].length() - subLength);
String[] rightNumberStr = rowStr[1].split("#");
int rightNumber = Integer.parseInt(rightNumberStr[0]);
rowStr[1] = rowStr[1].substring(rightNumberStr[0].length(), rowStr[1].length());
StringBuffer sb = new StringBuffer();
sb.append(rowStr[0]);
long calculate02 = calculate02(leftNumber, rightNumber);
sb.append(calculate02);
sb.append(rowStr[1]);
if (rowStr.length>2){
sb.append(substring);
return parseRule01(sb.toString());
}
return sb.toString();
}else {
return str;
}
}
//2.循环算# 将#清零
static String parseRule02(String str){
int RowLength = str.length();
int endIndex = 0;
String[] rowStr = str.split("#");
// int opNumber = rowStr.length - 1;
// System.out.println("opNumber "+opNumber);
// System.out.println("str "+str);
String substring = new String();
if (rowStr.length>2){
endIndex =rowStr[0].length() + rowStr[1].length()+1;
substring = str.substring(endIndex, RowLength);
}
if (rowStr.length>1){
int leftNumber = Integer.parseInt(rowStr[0]);
int rightNumber = Integer.parseInt(rowStr[1]);
long endNumber = calculate01(leftNumber,rightNumber);
StringBuffer sb = new StringBuffer();
sb.append(endNumber);
if (rowStr.length>2){
sb.append(substring);
return parseRule02(sb.toString());
}
return sb.toString();
}
return str;
}
static long calculate01(long x,long y){
return 2*x+3*y+4;
}
static long calculate02(long x,long y){
return 3*x+y+2;
}
}