Leecode_1006-笨阶层, 本来觉得这道题10分钟应该能ac,结果花了1个多小时,还是不够严谨仔细。
思路很简单,用栈保存每次乘除法运算的结果,碰到加减直接把操作数入栈,最后统一算。然后出栈的数字是表达式右边的数字,因为存在减法,所以我们要从前面开始算,也就是对栈做一个逆序然后先加再减。这样其实绕了一个弯,如果全是加法的话,从前往后算还是从后往前算都是一样的。所以我们碰到减法操作时入栈的时候保存负数即可。
import javax.jws.soap.SOAPBinding;import java.util.*;public class Main {public static void main(String[] args) {System.out.println(clumsy(1));}public static int clumsy(int N) {int count = 1;Stack<Integer> operand = new Stack<>();// 操作数int i = N - 1;operand.push(N);while(i > 0) {if(count % 4 == 1) {operand.push(operand.pop() * i);}else if(count % 4 == 2) {operand.push(operand.pop() / i);}else {operand.push(i);}//else {// operand.push(-i);//}i = i - 1;count++;}int m = operand.size();int[] sum = new int[m];//扭转栈,如果直接出栈就是从表达式后面算起,碰到减法会有问题,应该从前面开始算。while(!operand.isEmpty()){sum[--m] = operand.pop();}int result = sum[0];int flag = 0;for(int j = 1; j < sum.length; j++) {System.out.println(sum[j]);if(flag % 2 == 0)result = result + sum[j];elseresult = result - sum[j];flag++;}return result;}}
