The Indian Engineer

Problem 592 Fraction Addition and Subtraction

Posted on Last edited 3 mins

String Math Regex

Problem Statement

Link - Problem 592

Question

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.

Irreducible fraction

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

Solution

class Solution {
public:
    string fractionAddition(string exp) {
        int numer = 0, denom = 1;
        int idx = 0;
        int size = exp.size();

        while(idx<size){
            int sign = 1;
            if(exp[idx] == '+' || exp[idx] == '-'){
                if(exp[idx]=='-')
                    sign = -1;
                idx++;
            }

            int num = 0;
            while(idx<size && isdigit(exp[idx])){
                num = num*10 + (exp[idx]-'0');
                idx++;
            }

            num*=sign;
            idx++;

            int den = 0;
             while(idx<size && isdigit(exp[idx])){
                den = den*10 + (exp[idx]-'0');
                idx++;
            }

            numer = numer*den + num*denom;
            denom = denom*den;

            int GCD = gcd(abs(numer),denom);
            numer /= GCD;
            denom /= GCD;
        }
        return to_string(numer)+'/'+to_string(denom);
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
Traversal O(n) O(1)

Explanation

1. Intuition

2. Implementation