Algorithm


Problem Name: 592. Fraction Addition and Subtraction

Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.

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"

 

Constraints:

  • The input string only contains '0' to '9', '/', '+' and '-'. So does the output.
  • Each fraction (input and output) has the 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.

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


const fractionAddition = function (expression) {
  if (expression[0] === '-') expression = '0/1' + expression
  const terms = expression.split(/[+-]/g)
  const ops = '+' + expression.replace(/[^+-]/g, '')
  const nums = [],
    dens = []
  for (let term of terms) {
    let t = term.split('/')
    nums.push(parseInt(t[0]))
    dens.push(parseInt(t[1]))
  }
  const lcm = LCM(dens)
  const numSum = nums.reduce(
    (sum, num, i) => sum + ((+(ops[i] === '+') || -1) * num * lcm) / dens[i],
    0
  )
  const gcd = Math.abs(GCD(numSum, lcm))
  return numSum / gcd + '/' + lcm / gcd
}

function LCM(arr) {
  let res = arr[0]
  for (let i = 1; i  <  arr.length; i++) {
    res = (arr[i] * res) / GCD(arr[i], res)
  }
  return res
}

function GCD(a, b) {
  if (b === 0) return a
  return GCD(b, a % b)
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
expression = "-1/2+1/2"

Output

x
+
cmd
"0/1"

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def fractionAddition(self, e):
        
        def calc(i):
            l, r = i - 1, i + 1
            while l > 0 and e[l - 1].isdigit():
                l -= 1
            while r < len(e) - 1 and e[r + 1].isdigit():
                r += 1
            l = -int(e[l:i]) if l > 0 and e[l - 1] == "-" else int(e[l:i])
            r = int(e[i + 1:r + 1])
            return l, r
        
        def lcm(x, y):
            lcm = max(x, y)
            while True:
                if not lcm % x and not lcm % y:
                    return lcm
                lcm += 1
                
        def gcd(x, y):
            for i in range(min(x, y), 0, -1):
                if not x % i and not y % i:
                    return i
                
        n = d = None
        for i in range(len(e)):
            if e[i] == "/":
                if n:
                    n2, d2 = calc(i)
                    newD = lcm(d, d2)
                    newN = n * (newD // d) + n2 * (newD // d2)
                    if newN:
                        r = gcd(abs(newD), abs(newN))
                        n, d= newN // r, newD // r
                    else:
                        n, d = 0, 1
                else:
                    n, d = calc(i)
        return str(n) + "/" + str(d)
Copy The Code & Try With Live Editor

Input

x
+
cmd
expression = "-1/2+1/2""0/1"

Output

x
+
cmd
"0/1"
Advertisements

Demonstration


Previous
#591 Leetcode Tag Validator Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#593 Leetcode Valid Square Solution in C, C++, Java, JavaScript, Python, C# Leetcode