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.
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)"
1 2147483648 -1 -2147483648 -1 2147483648 1 -2147483648 -2147483648 -1 -2147483648 1 7 -12 89 -214748364 -89 214748364 -50 8 -50 -8 50 -7 4 33333 1 2 1 3 6 4 1 9
// 8ms, 59%
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if (denominator == 0 || numerator == 0) {
return "0";
}
string res = to_string((long)numerator / denominator);
if (res == "0" && ((numerator >> 31 & 1) ^ (denominator >> 31 & 1)))
res = "-" + res;
long rem = (long)numerator % denominator;
if (rem == 0)
return res;
res += ".";
unordered_map<int, int> mp;
while (rem != 0) {
if (mp.count(rem) > 0) {
res = res.substr(0, mp[rem]) + "(" + res.substr(mp[rem]) + ")";
return res;
}
mp[rem] = res.size();
rem *= 10;
res += to_string(abs(rem/denominator));
rem = rem % denominator;
}
return res;
}
};