邓心一 6 jaren geleden
bovenliggende
commit
25c241ca2a
1 gewijzigde bestanden met toevoegingen van 6 en 9 verwijderingen
  1. 6 9
      oj/bytedance-2019-interview/Calculator.java

+ 6 - 9
oj/bytedance-2019-interview/Calculator.java

@@ -25,33 +25,30 @@ public class Calculator {
         for (int i = 0; i <= exp.length;) {
             if (i == exp.length) {
                 if (ops.isEmpty()) break;
-                if (ops.peek() == '(') throw new Exception("Invalid exp!");
+                if (ops.peek() == '(') throw new Exception("Invalid expression!");
                 num.push(operate(ops.pop(), num.pop(), num.pop()));
                 continue;
             }
             switch (exp[i]) {
                 case '+': case '-':
                     if (ops.isEmpty() || ops.peek() == '(') {
-                        ops.push(exp[i]);
-                        i++;
+                        ops.push(exp[i++]);
                     } else {
                         num.push(operate(ops.pop(), num.pop(), num.pop()));
                     }
                     break;
                 case '*': case '/':
                     if (ops.isEmpty() || ops.peek() == '(' || ops.peek() == '+' || ops.peek() == '-') {
-                        ops.push(exp[i]);
-                        i++;
+                        ops.push(exp[i++]);
                     } else {
                         num.push(operate(ops.pop(), num.pop(), num.pop()));
                     }
                     break;
                 case '(':
-                    ops.push('(');
-                    i++;
+                    ops.push(exp[i++]);
                     break;
                 case ')':
-                    if (ops.isEmpty()) throw new Exception("Invalid exp!");
+                    if (ops.isEmpty()) throw new Exception("Invalid expression!");
                     if (ops.peek() == '(') {
                         ops.pop();
                         i++;
@@ -67,7 +64,7 @@ public class Calculator {
                     i = j;
             }
         }
-        if (num.size() != 1) throw new Exception("Invalid exp!");
+        if (num.size() != 1) throw new Exception("Invalid expression!");
         return num.peek();
     }