Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

For example,

- Given numerator = 1, denominator = 2, return "0.5".
- Given numerator = 2, denominator = 1, return "2".
- Given numerator = 2, denominator = 3, return "0.(6)".

**Understand the problem:**

0.166 ) 1.0001 0 <-- Remainder=1, mark 1 as seen at position=0. -640 <-- Remainder=4, mark 4 as seen at position=1. -364 <-- Remainder=4 was seen before at position=1, so the fractional part which is 16 starts repeating at position=1 => 1(6).

The key insight here is to notice that once the remainder starts repeating, so does the divided result.

You will need a hash table that maps from the remainder to its position of the fractional part. Once you found a repeating remainder, you may enclose the reoccurring fractional part with parentheses by consulting the position from the table.

The remainder could be zero while doing the division. That means there is no repeating fractional part and you should stop right away.

Just like the question Divide Two Integers, be wary of edge case such as negative fractions and nasty extreme case such as

`-2147483648 / -1`

.**Code (Java):**

public class Solution { public String fractionToDecimal(int numerator, int denominator) { if (denominator == 0) { return "inf"; } if (numerator == 0) { return "0"; } String result = ""; boolean neg = false; // Chceck if any negative number if ((numerator < 0) ^ (denominator < 0)) { neg = true; } // Transform to long to avoid overflow long num = numerator; long den = denominator; num = Math.abs(num); den = Math.abs(den); // Get the integer part long integer = num / den; result = String.valueOf(integer); // Get the remindar times 10 long remindar = (num % den) * 10; if (remindar == 0) { if (neg) { return "-" + result; } else { return result; } } Map<Long, Integer> map = new HashMap<Long, Integer>(); result += "."; while (remindar != 0) { if (map.containsKey(remindar)) { int pos = map.get(remindar); String part1 = result.substring(0, pos); String part2 = result.substring(pos, result.length()); result = part1 + "(" + part2 + ")"; if (neg) { return "-" + result; } else { return result; } } result += String.valueOf(remindar / den); map.put(remindar, result.length() - 1); remindar = (remindar % den) * 10; } if (neg) { return "-" + result; } else { return result; } } }

## No comments:

## Post a Comment