import java.util.ArrayList; import java.util.Stack; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { ArrayList<Integer> inputs = new ArrayList<Integer>(); Scanner in = new Scanner(System.in); String line = in.nextLine(); if(line != null && !line.isEmpty()) { int res = resolve(line.trim()); System.out.println(String.valueOf(res)); } } // write your code here public static int resolve(String expr) { String[] array = expr.split("\\s+"); Stack stack = new Stack(); int count = 0; for (int i = 0; i < array.length; i++){ if (array[i].equals("+")){ count--; int temp1 = 0; if (count >= 0){ temp1 = (int)stack.pop(); } else { return -1; } count--; int temp2 = 0; if (count >= 0){ temp2 = (int)stack.pop(); }else { return -1; } count++; stack.push(temp1+temp2); }else if (array[i].equals("*")){ count--; int temp1 = 0; if (count >= 0){ temp1 = (int)stack.pop(); } else { return -1; } count--; int temp2 = 0; if (count >= 0){ temp2 = (int)stack.pop(); }else { return -1; } count++; stack.push(temp1*temp2); }else if (array[i].equals("^")){ count--; int temp = 0; if (count >= 0){ temp = (int)stack.pop(); } else { return -1; } temp += 1; count++; stack.push(temp); }else { int temp = Integer.parseInt(array[i]); count++; if (count > 16){ return -2; }else { stack.push(temp); } } } return (int)stack.pop(); } } 我这样写ac了
点赞 评论

相关推荐

给🐭🐭个面试机会吧:我boss直聘天天有家教跟我打招呼😓
点赞 评论 收藏
分享
牛客网
牛客企业服务