"Efficient Fraction Addition and Simplification in Java"
Intuition\nThis code performs fraction addition and subtraction by processing a string expression of fractions. It first splits the expression into individual f
# Intuition\nThis code performs fraction addition and subtraction by processing a string expression of fractions. It first splits the expression into individual fractions using the signs (+ and -) as delimiters. The initial numerator num is set to 0, and the denominator den is set to 1. It then iterates through each fraction, parsing the numerator and denominator, and accumulates the result by converting each fraction to a common denominator and adding it to the cumulative sum. After processing all fractions, it checks if the numerator is zero; if so, it returns "0/1". Otherwise, it simplifies the fraction by dividing both the numerator and denominator by their greatest common divisor (GCD). Finally, it returns the simplified fraction in the form of a string "numerator/denominator". The gcd method is a helper function that computes the greatest common divisor using a subtraction-based approach.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```java []\nclass Solution {\n    public String fractionAddition(String expression) {\n        // Split the input string into individual fractions based on the \'+\' or \'-\' signs\n        String frs[] = expression.split("(?=[+-])");\n        \n        // Initialize the numerator as 0 and the denominator as 1\n        long num = 0, den = 1;\n\n        // Iterate over each fraction string\n        for (String fr : frs) {\n            // Split the fraction string into numerator and denominator\n            String[] curr = fr.split("/");\n            long a = Long.parseLong(curr[0]); // Parse the numerator\n            long b = Long.parseLong(curr[1]); // Parse the denominator\n            \n            // Update the cumulative numerator and denominator\n            num = num * b + a * den;\n            den = den * b;\n        }\n\n        // If the numerator is zero, return "0/1"\n        if (num == 0) return "0/1";\n        \n        // Calculate the greatest common divisor (GCD) of the numerator and denominator\n        long gcd = gcd(Math.abs(num), Math.abs(den));\n        \n        // Simplify the fraction by dividing both numerator and denominator by their GCD\n        num /= gcd;\n        den /= gcd;\n        \n        // Return the simplified fraction as a string\n        return num + "/" + den;\n    }\n\n    // Helper method to compute the greatest common divisor (GCD) using subtraction\n    private long gcd(long a, long b) {\n        if (a == b) return a;\n        if (a > b) return gcd(a - b, b);\n        return gcd(a, b - a);\n    }\n}\n\n```
['Java']