美文网首页
Fraction Addition and Subtractio

Fraction Addition and Subtractio

作者: stepsma | 来源:发表于2017-05-26 07:51 被阅读0次

    给出一个直观的解法,将每个数写成 "+(nom)/(denom)" 的string形式放到deque里,然后再把deque两两计算合并。计算时,要用到gcd来消公约数。写的比较长。

    class Solution {
    public:
        
        int gcd(int a, int b){
            return b == 0 ? a : gcd(b, a % b);
        }
        
        string calculate(string s1, string s2){
    
            int idx1 = s1.find_first_of('/'), idx2 = s2.find_first_of('/');
            int nom_1 = stoi(s1.substr(0, idx1)), nom_2 = stoi(s2.substr(0, idx2));
            int denom_1 = stoi(s1.substr(idx1+1)), denom_2 = stoi(s2.substr(idx2+1));
            int res_denom = denom_1 * denom_2; 
            int res_nom = nom_1 * denom_2 + nom_2 * denom_1;
            if(res_nom == 0) return"+0/1";
            
            int common = gcd(abs(res_nom), abs(res_denom));
            res_nom /= common; res_denom /= common;
            
            int sign = (res_nom * res_denom < 0) ? -1 : 1;
            return (sign == 1 ? '+' : '-') + to_string(abs(res_nom)) + '/' + to_string(abs(res_denom));
            
        }
    
        string fractionAddition(string expression) {
            if(expression.empty()) return "";
            if(isdigit(expression[0])) expression.insert(expression.begin(), '+');
            
            deque<string> dq;
            int start = 0;
            for(int i=1; i<=expression.length(); i++){
                if( i == expression.length() || expression[i] == '+' || expression[i] == '-'){
                    string temp = expression.substr(start, i-start);
                    dq.push_back(temp);
                    start = i;
                }
            }
            while(dq.size() >= 2){
                string s1 = dq.front(); dq.pop_front();
                string s2 = dq.front(); dq.pop_front();
                string res = calculate(s1, s2);
                //cout << s1 << " " << s2 << " " << res << endl;
                dq.push_front(res);
            }
            string res = dq.front();
            return res[0] == '-' ? res : res.substr(1);
        }
    };
    

    更简洁的solution参见如下,用regular expression split,再loop数组相加.

    https://discuss.leetcode.com/topic/89991/concise-java-solution

    其中,String[] fracs = expression.split("(?=[-+])"); 运用了zero-positive look ahead, 表明在+或-的前面split.

    相关文章

      网友评论

          本文标题:Fraction Addition and Subtractio

          本文链接:https://www.haomeiwen.com/subject/ewjtfxtx.html