592. Fraction Addition and Subtraction

;  |     Back to Homepage   |     Back to Code List


class Solution {
    public String fractionAddition(String exp) {
        int n = exp.length();

        List splittedAddSub = new ArrayList<>();
        List splittedDivide = new ArrayList<>();
        int addIndex = 0;

        for (int i = 0; i < n; i++) {
            char cur = exp.charAt(i);

            if (cur == '/') {
                if (i + 2 < n && exp.charAt(i + 2) == '0') {
                    splittedDivide.add(10);
                } else {
                    splittedDivide.add(exp.charAt(i + 1) - '0');
                }
                splittedAddSub.add(Integer.valueOf(exp.substring(addIndex, i)));
            } else if (cur == '+' || cur == '-') {
                addIndex = i;
            }
        }

        int curGcd = listGcd(splittedDivide, splittedDivide.size());
        int curLcm = listLcm(splittedDivide, splittedDivide.size());

        int res = 0;

        for (int i = 0; i < splittedAddSub.size(); i++) {
            int val = splittedAddSub.get(i);
            if (val < 0) {
                val = Math.abs(val);
                res -= curLcm / splittedDivide.get(i) * val;
            } else {
                res += curLcm / splittedDivide.get(i) * val;
            }
        }

        StringBuilder sb = new StringBuilder();
        if (res < 0) {
            curGcd = gcd(-res, curLcm);
            res = -res;
            sb.append('-');
        }
        
        int gcdEle = gcd(res, curLcm);
        sb.append(res / gcdEle);
        sb.append('/');
        sb.append(curLcm / gcdEle);
        return sb.toString();
    }

    private int gcd(int a, int b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }

    public int lcm(int a, int b) {
		return (a * b) / gcd(a, b);
	}

    public int listGcd(List num, int n) {
		if (n == 1) return num.get(n - 1);
		return gcd(num.get(n - 1), listGcd(num, n - 1));
	}

	public int listLcm(List num, int n) {
		if (n == 1) return num.get(n - 1);
		return lcm(num.get(n - 1), listLcm(num, n - 1));
    }
}