LeetcodeMay 15, 2026

Fraction Addition and Subtraction

Hazrat Ali

Leetcode

The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.

 

Example 1:

Input: expression = "-1/2+1/2"
Output: "0/1"

Example 2:

Input: expression = "-1/2+1/2+1/3"
Output: "1/3"

Example 3:

Input: expression = "1/3-1/2"
Output: "-1/6"

Solution
var fractionAddition = function(expression) {
    function gcd(a, b) {
        while (b !== 0) {
            let temp = b;
            b = a % b;
            a = temp;
        }
        return Math.abs(a);
    }

    let numerator = 0;
    let denominator = 1;

    let fractions = expression.match(/[+-]?\d+\/\d+/g);

    for (let frac of fractions) {

        let [num, den] = frac.split('/').map(Number);

        numerator = numerator * den + num * denominator;
        denominator = denominator * den;

        let g = gcd(numerator, denominator);

        numerator /= g;
        denominator /= g;
    }

    return numerator + "/" + denominator;
};



Comments