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了
点赞 评论

相关推荐

纯真的河老师在喝茶:第一个是这个时间点岗位少,第二个是这个简历重复度太高了,10个有9个简历差不多的
点赞 评论 收藏
分享
10-14 12:20
门头沟学院 Java
迷茫的大四🐶:摊牌了,我是25届的,你们也不招我
点赞 评论 收藏
分享
牛客网
牛客网在线编程
牛客网题解
牛客企业服务