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,
解决这题需要注意的问题是,当余数开始重复的时候,得到的小数点后位数同样开始重复。
例如:
此时得到余数为1,余第一个的余数重复,因此在余数为1得到的结果的数字处开始重复,即从字符串的第三位重复到目前字符串的最后一位,得到结果
代码如下:
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if (!numerator) return "0";
string result;
if ( numerator < 0 ^ denominator < 0) result += "-";
long long int n = numerator, d = denominator;
n = abs(n);
d = abs(d);
result += to_string(n / d);
long long int r = n % d;
if (!r) return result;
else result += ".";
unordered_map<int, int> reminder;
while (r)
{
if (reminder.find(r) != reminder.end())
{
result.insert(reminder[r], 1, ‘(‘);
result += ")";
break;
}
reminder[r] = result.size();
r *= 10;
result += to_string(r / d);
r = r % d;
}
return result;
}
};
LeetCode (29) Fraction to Recurring Decimal
原文地址:http://blog.csdn.net/angelazy/article/details/45559893