Loading...
Loading...
Write record Fraction(long num, long den). Its compact constructor rejects a zero denominator, moves a negative sign to the numerator and reduces the fraction to lowest terms, so equal values give equal records. Add the fractions on each line with a plus method that returns a new record. Print each line's sum, or Invalid when a fraction on the line has a zero denominator.
3/4 or -1/-2.<num>/<den> in lowest terms with a positive denominator (a whole number like 2 is 2/1, zero is 0/1), or Invalid.Example
Input
3 2 1/2 1/3 3 2/4 -1/4 3/-12 2 5/0 1/2
Output
5/6 0/1 Invalid
2/4 − 1/4 − 3/12 = 1/2 − 1/4 − 1/4 = 0; the third line has a zero denominator.
Try the problem first. Open one hint at a time.
In the compact constructor: if den < 0, flip both signs; then divide both by gcd(|num|, den). A static helper method may live in the record.
a/b + c/d = (a × d + c × b) / (b × d). Return new Fraction(...), and the constructor reduces it.
When a fraction throws, remember that the line is invalid but keep reading its tokens, so the next line starts in the right place.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor