// get string list List<String> rpnList = getListString(suffixNotation);
// test intresult= calculate(rpnList); System.out.println(result);
}
publicstatic List<String> getListString(String suffixNotaion) { String[] split = suffixNotaion.split(" "); List<String> list = newArrayList<String>(); for (String element : split) { list.add(element); } return list; }
// RPN: from left to right publicstaticintcalculate(List<String> list) { //only need one stack Stack<String> strings = newStack<>(); for (String s : list) { //regex if (s.matches("\\d+")) {//multi-number //push in numbers strings.push(s); } else { //when it comes to operator //calculate 2 numbers, then push in the result intnum2= Integer.parseInt(strings.pop()); intnum1= Integer.parseInt(strings.pop()); intresult=0; switch (s) { case"+": result = num1 + num2; break; case"-": result = num1 - num2; break; case"*": result = num1 * num2; break; case"%": result = num1 / num2; break; default: thrownewRuntimeException("There's something wrong with the operator."); } strings.push(String.valueOf(result)); } } return Integer.parseInt(strings.pop()); } }