166. Fraction to Recurring Decimal
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:
Example 2:
Example 3:
Constraints:
-231 <= numerator, denominator <= 231 - 1
denominator != 0
Solution:
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
boolean isNegative = false;
StringBuilder ans = new StringBuilder();
if (numerator < 0 && denominator > 0 || numerator > 0 && denominator < 0){
ans.append('-');
}
long quo = numerator / denominator; // 4 /333
long rem = numerator % denominator; // 4
ans.append(Math.abs(quo));//0
if (rem == 0){
return ans.toString();
}else{
ans.append('.'); // 0.
Map<Long, Integer> map = new HashMap<>();
while(rem != 0){ // rem = 4// rem = 40 // rem = 67
if (map.containsKey(rem)){
int pos = map.get(rem);
ans.insert(pos, '(');
ans.append(')');
break;
}else{
map.put(rem, ans.length()); // 4, 2// () // 40, 3 // 67, 4
rem = rem * 10; // 4 * 10 // 40 * 10 = 400 // 670
quo = rem/denominator; // 40 /333 = 0 // 400/333 = 1/ /670/333 = 2
rem = rem % denominator; // 40 % 333 = 40 // 400 % 333 = 67 // 670 - 666 = 4
ans.append(Math.abs(quo)); // 0.0 // 1 // 0.012
}
}
}
return ans.toString();
}
}
// TC: O(n)
// SC: O(n)