Ctrl K

Total of a Fraction Chain

Medium
The string chain is a sum and difference of fractions written as numerator/denominator, for example "1/3-1/2+5/6". The first fraction may be preceded by a minus sign; a plus sign is never written in front of it. Evaluate it and return the result as a string holding a fully reduced fraction p/q with a positive denominator. A negative result starts with a minus sign, a positive one has no sign. A whole number is written with denominator 1, such as "2/1", and zero is "0/1".
Example 1
chain="3/4-1/6" → '7/12'

3/4 − 1/6 = 9/12 − 2/12 = 7/12.

Example 2
chain="-2/3+1/6+1/2" → '0/1'

−4/6 + 1/6 + 3/6 = 0, and zero is written as 0/1.

Example 3
chain="5/2+3/2" → '4/1'

The sum is 4, a whole number, so the answer is 4/1.

Constraints
  • the chain holds 1 to 10 fractions
  • every numerator and denominator is an integer from 1 to 10
  • the string contains only digits and the characters /, +, -
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMultiplying Digit Strings MediumMultiply Complex Numbers in Strings MediumSolve for x MediumRover on Repeat MediumSum of Binary Strings Easy
loading Python…
Input
chain="3/4-1/6"
Expected
'7/12'

Run checks the first 3 tests in your browser. Submit checks all 96 tests on the server, hidden ones included.