Problem Statement
A rational number is defined as a/b, where a and b are integers, and b is greater than 0. Furthermore, a rational number can be written as a decimal that has a group of digits that repeat indefinitely. A common method of writing groups of repeating digits is to place them inside parentheses like 2.85(23) = 2.852323 ... 23...
Given a decimal representation of a rational number convert it to a fraction formatted as "numerator/denominator", where both numerator and denominator are integers. The fraction must be reduced. In other words, the denominator must be as small as possible, but greater than zero.
Definition
- Class:
- RecurringNumbers
- Method:
- convertToFraction
- Parameters:
- String
- Returns:
- String
- Method signature:
- String convertToFraction(String decimal)
- (be sure your method is public)
Constraints
- decimal will have between 3 and 10 characters inclusive.
- decimal will contain only characters '0' - '9', '.', '(' and ')'.
- The second character in decimal will always be '.'.
- There will be at most one '(' and ')' in decimal.
- '(' in decimal will be followed by one or more digits ('0' - '9'), followed by ')'.
- ')' in decimal will not be followed by any other character.
Examples
"0.(3)"
Returns: "1/3"
0.(3) = 0.333... = 1/3"1.3125"
Returns: "21/16"
Note there are no recurring digits here, although we could write it as 1.3125(0) or 1.3124(9)."2.85(23)"
Returns: "14119/4950"
"9.123(456)"
Returns: "3038111/333000"
"4.(9)"
Returns: "5/1"
As strange as it seems, but 4.999... is the same as 5.