Java AC solution beat 68%


  • 0
    A
    public String fractionAddition(String expression) {
        int num = 0, den = 1, prevIdx = 0;
        for(int i=1; i<expression.length(); i++){
            if(expression.charAt(i)=='+' || expression.charAt(i)=='-' || i == expression.length()-1){
                int cur[] = addOperation(expression.substring(prevIdx, i==expression.length()-1 ? i+1 : i), num, den);
                num = cur[0];
                den = cur[1];
                prevIdx = i;
            }
        }
        return num + "/" + den;
    }
    public int[] addOperation(String str, int num, int den){
        String[] strs = str.split("/");
        long n = Long.valueOf(strs[0].trim());
        long d = strs.length == 1 ? 1 : Long.valueOf(strs[1].trim());
        n = n * den + num * d;
        d = d * den;
        long cd = Math.abs(lcd(n, d));
        return new int[]{(int)(n/cd), (int)(d/cd)};
    }
    public long lcd(long a, long b){
        return a==0 || b==0 ? a+b : lcd(b, a%b);
    }

Log in to reply
 

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