java 592. Fraction Addition和Subtraction.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 592. Fraction Addition和Subtraction.java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public int gcd (int x, int y) {
        return y == 0 ? Math.abs(x) : gcd(y, x % y); // "1/3-1/2" => "-1/6", otherwise "1/-6"
    }
    public String fractionAddition(String expression) {
        Scanner sc = new Scanner(expression).useDelimiter("/|(?=[+-])");
        int numerator = 0, denominator = 1;
        while(sc.hasNext()) {
            int a = sc.nextInt(), b = sc.nextInt();
            numerator = numerator * b + denominator * a;
            denominator *= b; 
            int g = gcd(denominator, numerator);
            numerator /= g;
            denominator /= g;
        }
        return numerator + "/" + denominator;
    }
}

以上是关于java 592. Fraction Addition和Subtraction.java的主要内容,如果未能解决你的问题,请参考以下文章

java 592. Fraction Addition和Subtraction.java

java 592. Fraction Addition和Subtraction.java

java 592. Fraction Addition和Subtraction.java

java 592. Fraction Addition和Subtraction.java

java 592. Fraction Addition和Subtraction.java

[leetcode-592-Fraction Addition and Subtraction]