0166. Fraction to Recurring Decimal
https://leetcode.com/problems/fraction-to-recurring-decimal
Description
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.
If multiple answers are possible, return any of them.
It is guaranteed that the length of the answer string is less than 104
for all the given inputs.
Example 1:
**Input:** numerator = 1, denominator = 2
**Output:** "0.5"
Example 2:
**Input:** numerator = 2, denominator = 1
**Output:** "2"
Example 3:
**Input:** numerator = 2, denominator = 3
**Output:** "0.(6)"
Example 4:
**Input:** numerator = 4, denominator = 333
**Output:** "0.(012)"
Example 5:
**Input:** numerator = 1, denominator = 5
**Output:** "0.2"
Constraints:
-231 <= numerator, denominator <= 231 - 1
denominator != 0
ac
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.
**/
Last updated
Was this helpful?