Fraction Addition and Subtraction

LeetCode Q 592 - Fraction Addition and Subtraction

Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result should be irreducible fraction. If your final result is an integer, say 2, you need to change it to the format of fraction that has denominator 1. So in this case, 2 should be converted to 2/1.

Example 1: Input:"-1/2+1/2" ; Output: "0/1"
Example 2: Input:"-1/2+1/2+1/3" ; Output: "1/3"
Example 3: Input:"1/3-1/2" ; Output: "-1/6"
Example 4: Input:"5/3+1/3" ; Output: "2/1"
Note:

  • The input string only contains '0' to '9', '/', '+' and '-'. So does the output.
  • Each fraction (input and output) has format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.
  • The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1,10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
  • The number of given fractions will be in the range [1,10].
  • The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.

Solution:

The solution is quite intuitive. First we find each fraction, and then sum them up. To obtain the irreducible fraction result, we divide numerator and denominator by their greatest common divisor (gcd).

public String fractionAddition(String exp) {
    if (exp == null || exp.length() == 0) return exp;

    List<Character> list = new ArrayList<>();

    if (exp.charAt(0) != '-') list.add('+');

    for (int i = 0; i < exp.length(); i++)
        if (exp.charAt(i) == '+' || exp.charAt(i) == '-')
            list.add(exp.charAt(i));

    String[] strs = exp.split("(\\+)|(-)");

    int i = 0, prevNum = 0, prevDen = 1;

    for (String str: strs) {
        if (str.length() == 0) continue;

        String[] nums = str.split("/");

        int num = Integer.parseInt(nums[0]);
        int den = Integer.parseInt(nums[1]);

        if (list.get(i++) == '+')
            prevNum = prevNum * den + prevDen * num;
        else 
            prevNum = prevNum * den - prevDen * num;

        prevDen = den * prevDen;

        int g = Math.abs(gcd(prevNum, prevDen));

        prevNum /= g; prevDen /= g;
    }

    return prevNum + "/" + prevDen;
}

private int gcd(int a, int b) {
    if (a == 0 || b == 0) return a + b;
    return gcd(b, a % b);
}

Tips:

  1. Fraction Addition

a / b + c / d = (a * d + b * c) / b * d.

  1. Regular Expression (regex) Analysis
"(\\+)|(-)"

first part: \\+ => \\ can be understood as a single \ in the regex, which is then used to escape the +. This regax means a signle + ;

second part: - => This means a single - ;

first part | second part => find first part or second part.

Therefore "(\\+) | (-)" means find + or - .
  1. Greatest Common Divisor

Here, we use Euclidean Algorithm to get gcd. The Euclidean Algorithm for finding GCD(A,B) is as follows:

  • If A = 0 then GCD(A,B)=B, since the GCD(0,B)=B, and we can stop.
  • If B = 0 then GCD(A,B)=A, since the GCD(A,0)=A, and we can stop.
  • Write A in quotient remainder form (A = B⋅Q + R)
  • Find GCD(B,R) using the Euclidean Algorithm since GCD(A,B) = GCD(B,R).
source

So our gcd code is as follows.

private int gcd(int a, int b) {
    if (a == 0 || b == 0) return a + b;
    return gcd(b, a % b);
}

   Reprint policy


《Fraction Addition and Subtraction》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC