592. Fraction Addition and Subtraction #383
-
Topics: Given a string The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
We need to carefully parse the input string and perform arithmetic operations on the fractions. The steps are as follows:
Let's implement this solution in PHP: 592. Fraction Addition and Subtraction <?php
/**
* @param $a
* @param $b
* @return float|int
*/
function gcd($a, $b) {
while ($b != 0) {
$temp = $b;
$b = $a % $b;
$a = $temp;
}
return abs($a);
}
/**
* @param $numerator1
* @param $denominator1
* @param $numerator2
* @param $denominator2
* @return float[]|int[]
*/
function addFractions($numerator1, $denominator1, $numerator2, $denominator2) {
// Find the common denominator
$commonDenominator = $denominator1 * $denominator2;
$newNumerator = $numerator1 * $denominator2 + $numerator2 * $denominator1;
// Simplify the fraction
$commonGCD = gcd($newNumerator, $commonDenominator);
$simplifiedNumerator = $newNumerator / $commonGCD;
$simplifiedDenominator = $commonDenominator / $commonGCD;
return [$simplifiedNumerator, $simplifiedDenominator];
}
/**
* @param String $expression
* @return String
*/
function fractionAddition($expression) {
// Match fractions with regex
preg_match_all('/[+-]?[0-9]+\/[0-9]+/', $expression, $matches);
$fractions = $matches[0];
// Start with a base fraction of 0/1
$numerator = 0;
$denominator = 1;
foreach ($fractions as $fraction) {
list($num, $den) = explode('/', $fraction);
list($numerator, $denominator) = addFractions($numerator, $denominator, intval($num), intval($den));
}
// Return the result as a fraction
return $numerator . '/' . $denominator;
}
// Example usage
echo fractionAddition("-1/2+1/2"); // Output: "0/1"
echo "\n";
echo fractionAddition("-1/2+1/2+1/3"); // Output: "1/3"
echo "\n";
echo fractionAddition("1/3-1/2"); // Output: "-1/6"
?> Explanation:
Test Cases:
This solution handles all the required operations and returns the correct output for each given expression. |
Beta Was this translation helpful? Give feedback.
We need to carefully parse the input string and perform arithmetic operations on the fractions. The steps are as follows:
Let's implement this solution in PHP: 592. Fraction Addition and Subtraction