关注
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了
查看原帖
点赞 评论
相关推荐
牛客热帖
更多
正在热议
更多
# 牛客吐槽大会 #
15067次浏览 229人参与
# 实习,不懂就问 #
159994次浏览 1424人参与
# 晒晒你司的新年福利 #
1483次浏览 25人参与
# 国企秋招,你投了吗? #
59048次浏览 378人参与
# 程序员找工作至少要刷多少题? #
1785次浏览 27人参与
# 暑假倒计时,你都干了些啥? #
39616次浏览 207人参与
# 硬件/芯片公司工作体验 #
146911次浏览 960人参与
# 软开人,秋招你打算投哪些公司呢 #
178719次浏览 1359人参与
# 硬件人秋招进展 #
269489次浏览 3983人参与
# 毕业后不工作的日子里我在做什么 #
233048次浏览 1691人参与
# 帆软软件工作体验 #
11584次浏览 55人参与
# 运营人求职交流聚集地 #
208726次浏览 1091人参与
# 学历or实习经历,哪个更重要 #
232936次浏览 1225人参与
# 实习越久越好,还是多多益善? #
69172次浏览 332人参与
# AI“智障”时刻 #
23873次浏览 119人参与
# 你觉得实习能学到东西吗 #
134982次浏览 1454人参与
# 第一份工作应该只看薪资吗 #
233995次浏览 1855人参与
# 电信求职进展汇总 #
39810次浏览 197人参与
# 关于春招你都做了哪些准备? #
125928次浏览 717人参与
# AI求职实录 #
20798次浏览 503人参与
