C++ parse with stringstream


  • 0
    B
    class Solution {
    public:
        string fractionAddition(string expression) {
            stringstream ss(expression);
            int num, dem, num1, dem1;
            char buff, opt;
            ss >> num >> buff >> dem;
            while(ss >> opt >> num1 >> buff >> dem1)
            {
                int sign = opt == '+' ? 1 : -1; 
                num = num * dem1 + sign * num1 * dem;
                dem *= dem1;
                int lcd = gcd(abs(num), abs(dem));
                dem /= lcd;
                num /= lcd;
            }
            return to_string(num) + "/" + to_string(dem);
        }
        
        int gcd(int num, int dem)
        {
            if(num > dem) return gcd(dem, num);
            if(num == 0) return dem;
            return gcd(num, dem % num);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.