Fraction Addition and Subtraction
Example 1:
Input:"-1/2+1/2"
Output: "0/1"
Example 2:
Input:"-1/2+1/2+1/3"
Output: "1/3"
Example 3:
Input:"1/3-1/2"
Output: "-1/6"
Example 4:
Input:"5/3+1/3"
Output: "2/1"Example 1:
Input:"-1/2+1/2"
Output: "0/1"
Example 2:
Input:"-1/2+1/2+1/3"
Output: "1/3"
Example 3:
Input:"1/3-1/2"
Output: "-1/6"
Example 4:
Input:"5/3+1/3"
Output: "2/1" public class Solution {
public String fractionAddition(String expression) {
String[] split = expression.split("(?=[-+])");
long num1 = 0, den1 = 1;
for (String fraction : split) {
long num2 = Integer.parseInt(fraction.split("/")[0]);
long den2 = Integer.parseInt(fraction.split("/")[1]);
long gcd = gcd(Math.abs(den1), Math.abs(den2));
num1 = (num1 * den2 + num2 * den1) / gcd;
den1 = den1 * den2 / gcd;
gcd = gcd(Math.abs(den1), Math.abs(num1));
den1 /= gcd;
num1 /= gcd;
}
return num1 + "/" + den1;
}
private long gcd(long a, long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
}