Friday, October 13, 2017

592. Fraction Addition and Subtraction

https://leetcode.com/problems/fraction-addition-and-subtraction/description/
Solution. gcd(a,b) find the greatest common divisor. Then the irreducible fraction can be found.
    string fractionAddition(string exp) {
        string delim = "+-";
        if(exp[0]>='0' && exp[0]<='9') exp = "+" + exp;
        size_t pos = 0, start = 0, dv;
        string res = "", b;
        int n = 0, d = 1, nb, db, nn;
        while(start != string::npos){
            pos = exp.find_first_of(delim, start+1);
            b = exp.substr(start, pos - start);
            dv = b.find_first_of("/", 0);
            nb = stoi(b.substr(0, dv));
            db = stoi(b.substr(dv+1));
           
            n = n*db + d*nb;
            d = d*db;
            int g = gcd(abs(n), d);
            n /= g;
            d /= g;

            start = pos;
        }
        return res + to_string(n) + "/" + to_string(d);
    }
    int gcd(int a, int b) {
        if(b == 0) return a;
        return gcd(b, a%b);
    }

No comments:

Post a Comment