Java, 原创,

面试题代码Java实现:根据给定的字符串计算结果,只含乘法和加法

以下是面试要求:

String str = "1*2+3";
// 计算字符串给出的结果, 只含有加法和乘法

个人实现如下, 未作优化:

import java.util.*;

// 必须定义 `ShowMeBug` 入口类和 `public static void main(String[] args)` 入口方法
public class ShowMeBug {
  public static void main(String[] args) {
     //String str = "1*2+3";
      // String str = "3+2+4*2";
       String str = "24*5+5*2";
    var result = getMathResult(str);
      System.out.println(result);
  }
    
    public static String getMathResult(String str) {
        Stack methodStack = new Stack();
        Stack dataStack = new Stack();
        
        var strChars = str.toCharArray();
        var tmpStr = "";
        for (var strChar : strChars) {
            if (strChar == '*' || strChar == '+') {
                methodStack.push(strChar);
                dataStack.push(tmpStr);
                tmpStr = "";
            } else {
                tmpStr += strChar;
            }
        }
        dataStack.push(tmpStr);
        var result = methCompute(dataStack, methodStack);
        return String.valueOf(result);
    }
    
    private static Integer methCompute(Stack dataStack, Stack methodStack) {
        var result = Integer.valueOf(dataStack.pop().toString());
        var tmpMethod = methodStack.pop();
        var tmpRes = Integer.valueOf(dataStack.pop().toString());
        if (dataStack.size() > 0) {
            while(dataStack.size() > 0) {
                var tmpM = methodStack.pop();
                var tmpR = Integer.valueOf(dataStack.pop().toString());
                if (tmpM.equals('*')) {
                    tmpRes = tmpRes * tmpR;
                } else {
                    result = tmpMethod.equals('*') ? result * tmpRes : result + tmpRes;
                    tmpMethod = tmpM;
                    tmpRes = tmpR;
                }
            }
            
        }
        result = tmpMethod.equals('*') ? result * tmpRes : result + tmpRes;
        return result;
    }
}

虽然在规定的时间没能实现, 但是还是要把他写出来保留。

(117)

Related Post