Addition of Fractions (with.Java)
This is the “Addition of Fractions” problem.
We’re going to learn about it by solving coding test problems, reflecting on the problems we solved, and exploring other ways to solve them.
Let’s start with the problem
Problem
You are given the parameters numer1, denom1, the numerator and denominator of the first fraction, and numer2, denom2, the numerator and denominator of the second fraction.
Complete the solution function so that it returns an array containing the numerators and denominators in order when the two fractions are added and represented as an expected fraction.
Example input and output
numer1 | denom1 | numer2 | denom2 | result |
---|---|---|---|---|
1 | 2 | 3 | 4 | [5, 4] |
9 | 2 | 1 | 3 | [29, 6] |
My solution to the ### problem
class Solution {
public int[] solution(int numer1, int denom1, int numer2, int denom2) {
int newNumer = numer1 * denom2 + numer2 * denom1;
int newDenom = denom1 * denom2;
int gcd = findGCD(newNumer, newDenom);
newNumer /= gcd;
newDenom /= gcd;
int[] result = {newNumer, newDenom};
return result;
}
public int findGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
} return Math.abs(a);
}
Solution Explanation
int newNumer = numer1 _ denom2 + numer2 _ denom1;: Computes a new numerator, newNumer, by adding the numerators of the two given fractions.
int newDenom = denom1 * denom2;: Computes a new denominator newDenom by multiplying the denominators of the two given fractions.
int gcd = findGCD(newNumer, newDenom);: Call the findGCD function to find the greatest common divisor (gcd) of newNumer and newDenom.
newNumer /= gcd; and newDenom /= gcd;: Divide newNumer and newDenom by the greatest common divisor to get the expected fraction.
int[] result = {newNumer, newDenom};: Put the expected fractions, newNumer and newDenom, into an array and store them in the result array.
return result;: Returns the calculated result, the expected fraction.
The findGCD function uses Euclidean arithmetic to compute the greatest common divisor of two numbers. The code performs simple fraction operations, adding the two fractions and normalizing the result to the common denominator.