If the fractional part is repeating, enclose the repeating part in parentheses.
**Input:** numerator = 1, denominator = 2
**Output:** "0.5"
**Input:** numerator = 2, denominator = 1
**Output:** "2"
**Input:** numerator = 2, denominator = 3
**Output:** "0.(6)"
**Input:** numerator = 4, denominator = 333
**Output:** "0.(012)"
**Input:** numerator = 1, denominator = 5
**Output:** "0.2"
So tedious handling those stackoverflow edge cases.
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
//edge cases
if (numerator == 0) return "0";
if (denominator == 0) return "";
StringBuilder sb = new StringBuilder();
Map<Long, Integer> map = new HashMap<Long, Integer>();
// > 0
boolean positive = numerator >= 0 && denominator >= 0 || numerator < 0 && denominator < 0;
long num = Math.abs((long)numerator);
long den = Math.abs((long)denominator);
long first = num / den;
// decimal
long n = num % den;
int digits = 0;
int repeatDigit = -1;
while (n != 0) {
if (map.containsKey(n)) {
repeatDigit = map.get(n);
break;
}
map.put(n, digits);
sb.append("" + n * 10 / den);
n = n * 10 % den;
digits++;
}
String decimal = sb.toString();
// output
String res = "";
if (repeatDigit >= 0) {
res = String.format("%d.%s(%s)", first, decimal.substring(0, repeatDigit), decimal.substring(repeatDigit));
} else if (decimal.length() > 0) {
res = "" + first + "." + decimal;
} else {
res = "" + first;
}
return positive ? res : "-" + res;
}
}
/**
before dot: n / d
decimal: n = n % d * 10, keep doing
when repeat (hashmap record position), stop, the part repeats: map.get(i) - last one, enclose with parentheses.
**/