import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); Stack<String> stack = new Stack<String>(); int count = 0, sum = 0; for(int i=0; i<s.length(); i++) { if(s.charAt(i) == ' ') { continue; } if(s.charAt(i) != ')') { stack.push(String.valueOf(s.charAt(i))); }else { String c = stack.pop(); int temp = 0; List<Integer> list = new ArrayList<Integer>(); while(!c.equals("(") && !stack.empty()) { if(c.equals("+") ) { for(int j=0; j<list.size(); j++) { temp += list.get(j); } }else if(c.equals("-")) { temp = list.get(list.size()-1); for(int j=list.size()-2; j>=0; j--) { temp -= list.get(j); } }else if(c.equals("*")) { temp = list.get(0); for(int j=1; j<list.size(); j++) { temp *= list.get(j); } }else if(c.equals("/")) { temp = list.get(list.size()-1); for(int j=list.size()-2; j>=0; j--) { temp /= list.get(j); } }else { int z = Integer.valueOf(String.valueOf(c)); list.add(z); } c= stack.pop(); } String cc = String.valueOf(temp); stack.push(cc); } } System.out.println(stack.pop()); scanner.close(); } } |
Double click to view unformatted code.