Leetcode: Fraction Addition and Subtraction
The following question is a representation of Fraction Addiction and Subtracted, and it is tested multiple times by the IXL company. Here's a commemorative "Math" by Dash from the Incredibles.
The question goes as follows:
Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result should be an irreducible fraction. If your final result is an integer, for example 2, you need to change the format so it has the denominator 1. The input has irreducible fractions. Find the common denominator or greatest common factor and use the Euclidean rule to give the result that is so desired, and is in the range of 32 bit integers up to 2^31 - 1 from 2^-31.
Here are some examples:
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"
So we need to split the expression into addition and subtraction functions and add each function for all the fractions. The rest is basically parsing.
class Solution {
//First take a regular expression, splitting with the +- signs
String[] tokens = expression.split("(?=[+-])");
int len = tokens.length;
int[] numerators = new int[len];
int[] denominators = new int[len];
//split the numerator and denominator through the parseInt() method.
for(int i = 0; i < len; i++){
numerators[i] = Integer.parseInt(tokens[i].split("/")[0]);
denominators[i] = Integer.parseInt(tokens[i].split("/")[1]);
}
//multiply all the denominators to get the greatest common factor.
long denominator = 1;
long numerator = 0;
for(int i = 0; i < len; i++) {
denominator *= denominators[i];
}
//get the numerator congruent to this denominator.
for(int i = 0; i < len; i++) {
numerator += denominator * numerators[i] / denominators[i];
}
long A = Math.abs(gcd(denominator, numerator));
//divide that by the gcd to get the simplest form.
String res = numerator / A + "/" + denominator / A;
return res;
}
private long gcd(long x, long y) {
//keep reducing the fraction until achieved result
if(y == 0) return x;
return gcd(y, x % y);
}
}
I don't really understand how the gcd function works, so I'll look it up. Basically the euclidean algorithm reduces the gcd until the common divisor = 0 else it takes the modulus of the numerator to the denominator and switch the positions of the numerator and denominator.

Comments
Post a Comment