[java] LC 224. Basic Calculator

Viewer

copydownloadembedprintName: LC 224. Basic Calculator
  1. class Solution {
  2.     private int index;
  3.     private String s;
  4.     public int calculate(String s) {
  5.         this.s = s.replace(" """) + " ";
  6.         index = 0;
  7.         int v = readExpression();
  8.         if (index != s.length() - 1) {
  9.             // error
  10.         }
  11.         return v;
  12.     }
  13.     // EXPRESSION := TERM [+- TERM]...
  14.     int readExpression() {
  15.         int v = readTerm();
  16.         while (s.charAt(index) == '+' || s.charAt(index) == '-') {
  17.             if (s.charAt(index) == '+') {
  18.                 index ++;
  19.                 v += readTerm();
  20.             } else {
  21.                 index ++;
  22.                 v -= readTerm();
  23.             }
  24.         }
  25.         return v;
  26.     }
  27.     // TERM := INT [*/ INT]...
  28.     int readTerm() {
  29.        int v = readInt();
  30.         while (s.charAt(index) == '*' || s.charAt(index) == '/') {
  31.             if (s.charAt(index) == '*') {
  32.                 index ++;
  33.                 v *= readInt();
  34.             } else {
  35.                 index ++;
  36.                 v /= readInt();
  37.             }
  38.         }
  39.         return v;
  40.     }
  41.     // INT :+ [0-9]+ | (EXPRESSION)
  42.     int readInt() {
  43.         int v = 0;
  44.         if (Character.isDigit(s.charAt(index))) {
  45.             while (Character.isDigit(s.charAt(index))) {
  46.                 v = v * 10 + (s.charAt(index) - '0');
  47.                 index++;
  48.             }
  49.         } else if (s.charAt(index) == '(') {
  50.             index++;
  51.             v = readExpression();
  52.             if (s.charAt(index) != ')') {
  53.                 //error
  54.             }
  55.             index++;
  56.         }
  57.         return v;
  58.     }
  59. }

Editor

You can edit this paste and save as new:


File Description
  • LC 224. Basic Calculator
  • Paste Code
  • 25 Jul-2021
  • 1.58 Kb
You can Share it: