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)".
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
string ret;
long long ln = numerator, ld = denominator; // int型-2147483648取反导致溢出
long long quotient, newNumerator;
bool isRepeat = false;
if ((ln < 0 && ld > 0) || (ln > 0 && ld < 0)) {
ret += "-";
}
ln = ln < 0? -ln : ln;
ld = ld < 0? -ld : ld;
quotient = ln / ld;
newNumerator = ln - quotient * ld;
ret += to_string(quotient);
if (newNumerator == 0) return ret;
ret += ".";
//保证分子小于分母
vector< vector<long long> > result;
unsigned long i, j, k;
for (i = 0; i < ld; i++) {
quotient = 10 * newNumerator / ld;
result.push_back({newNumerator, quotient});
newNumerator = 10 * newNumerator - quotient * ld;
//除清 非循环小数
if (newNumerator == 0) {
for (k = 0; k <= i; k++)
ret += to_string(result[k][1]);
return ret;
}
//小数循环部分检测
for (j = 0; j < result.size(); j++) {
if (result[j][0] == newNumerator) {
isRepeat = true;
break;
}
}
if (isRepeat == true) {
for (k = 0; k < j; k++) {
ret += to_string(result[k][1]);
}
ret += "(";
for (k = j; k <= i; k++) {
ret += to_string(result[k][1]);
}
ret += ")";
return ret;
}
}
return ""; // never go here
}
};