1.面试问题
2.思路我的想法是,拿到字符串后,先拿最后一个(') 然后取最后一个 '(' 后的 ")",即得到一个小括号表达式,然后我们对表达式进行四个操作,替换计算结果()表达式。对 [] 处理方法也是如此。直接粘贴最终实现代码。
3.具体代码
public static void main(String[] args) { String str = *[1+3]; while(str.contains([]) { while(str.contains() { String b = str.substring(str.lastIndexOf('); ////拿到表达式的最后一个 ( int endnum = b.indexOf(')') + str.lastIndexOf('(');////拿到表达式的最后一个 ( 后面的 ) 形成()表达式,下标是str的下标 String inner = str.substring(str.lastIndexOf('),endnum+1);//截取()表达式内容 String r = inner.substring(1,inner.length()-1);//去除()//// String r = StringUtils.strip(inner,"()");//去掉 () String v = String.valueOf(doCalculation(r));//计算四个运算 String newv = str.replace(inner,v);;//替换结算结果()表达式 str = newv; } String b = str.substring(str.lastIndexOf('');//思路同 处理() int endnum = b.indexOf(']') + str.lastIndexOf('['); String inner = str.substring(str.lastIndexOf(''),endnum+1); String r = inner.substring(1,inner.length()-1); String v = String.valueOf(doCalculation(r)); String newv = str.replace(inner,v);; str = newv; } System.out.println(doCalculation(str)); } private static double doCalculation(String formula) { ArrayList<Double> values = new ArrayList<Double>(); ArrayList<String> operators = new ArrayList<String>(); int curPos = 0; int prePos = 0; int minus = 0; for (char s : formula.toCharArray()) { if ((s == '+' || s == '-' || s == '*' || s == '/') && minus !=0 && minus !=2) { values.add(Double.parseDouble(formula.substring(prePos, curPos).trim())); operators.add("" + s); prePos = curPos + 1; minus = minus +1; }else{ minus =1; } curPos++; } values.add(Double.parseDouble(formula.substring(prePos).trim())); char op; for (curPos = 0; curPos <= operators.size() - 1; curPos++) { op = operators.get(curPos).charAt(0); switch (op) { case '*': values.add(curPos, values.get(curPos) * values.get(curPos + 1)); values.remove(curPos + 1); values.remove(curPos + 1); operators.remove(curPos); curPos = -1; break; case '/': values.add(curPos, values.get(curPos) / values.get(curPos + 1)); values.remove(curPos + 1); values.remove(curPos + 1); operators.remove(curPos); curPos = -1; break; } } for (curPos = 0; curPos <= operators.size() - 1; curPos++) { op = operators.get(curPos).charAt(0); switch (op) { case '+': values.add(curPos, values.get(curPos) + values.get(curPos + 1)); values.remove(curPos + 1); values.remove(curPos + 1); operators.remove(curPos); curPos = -1; break; case '-': values.add(curPos, values.get(curPos) - values.get(curPos + 1)); values.remove(curPos + 1); values.remove(curPos + 1); operators.remove(curPos); curPos = -1; break; } } return values.get(0).doubleValue(); }
4.计算结果