Easy java solution, 11ms


  • 0
    C
    public String fractionAddition(String expression) {
        if (expression.length() < 3) {
          return "";
        }
        int nu = 0;
        int de = 1;
        boolean neg = false;
        for (int i = 0; i < expression.length(); i++) {
          char c = expression.charAt(i);
          if (c == '+') {
            neg = false;
          } else if (c == '-') {
            neg = true;
          }
          if (c != '/') {
            continue;
          }
          int currentDe = getNum(expression, i + 1, true);
          int nuNum = getNum(expression, i - 1, false);
          int currentNu = neg ? -nuNum : nuNum;
          int newDe = getLCM(de, currentDe);
          nu = newDe / de * nu + newDe / currentDe * currentNu;
          de = newDe;
        }
    
        int gcd = getLCD(Math.abs(nu), de);
        if (gcd != 1) {
          nu /= gcd;
          de /= gcd;
        }
    
        return nu + "/" + de;
      }
    
      private int getNum(String expression, int i, boolean start) {
        int index = i;
        while (index >= 0 && index < expression.length() && Character.isDigit(expression.charAt(index))) {
          index = start ? index + 1 : index - 1;
        }
        return Integer.parseInt(start ? expression.substring(i, index) : expression.substring(index + 1, i + 1));
      }
    
      private int getLCM(int a, int b) {
        return a * (b / getLCD(a, b));
      }
    
      private int getLCD(int a, int b) {
        // Euclidean algorithm with recursive
        return a == 0 || b == 0 ? a + b : getLCD(b, a % b);
      }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.