Decimal to Fraction
InterviewTime limit1sMemory limit128 MB
Convert a decimal string, with an optional repeating block in parentheses, into the exact fraction in lowest terms.
- Level
Medium5 of 10
- Topics
- Math, Number theory, String, Implementation
- Solved
- No attempts yet
Problem
When a rational number is written as a decimal, there are two cases: the decimal has finitely many digits after the point (for example, ), or from some position onward a fixed block of digits repeats forever (for example, ).
Given such a decimal, write a program that expresses it as a fraction in lowest terms.
Input
The first line contains the number of test cases, which is at most . Each of the following lines contains one decimal.
Every decimal begins with 0.. After that come to digits, followed by an optional number wrapped in parentheses. The number inside the parentheses has length between and and denotes the block of digits that repeats forever.
Each decimal always contains at least one nonzero digit, and the number inside the parentheses is never made up entirely of s or entirely of s.
Output
For each test case, print the fraction representation of the given decimal on its own line. The numerator and denominator must be coprime (the fraction must be in lowest terms).