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.
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)".
注意一:将 int 型 变为long long 来处理
注意二:if((num11<0) ^ (num22<0)) 代表有一个为负 巧妙使用异或
注意三: to_string() 函数 将整数变为字符串
注意四:当每一次都要查找时,一定用map来存
class Solution {
public:
string fractionToDecimal(int num11, int num22)
{
if(num11 == 0)
return "0";
int sign = 1;
if((num11 < 0) ^ (num22 < 0))
sign = -1;
long long n = num11;
long long d = num22;
n = abs(n);
d = abs(d);
map<long long, int> m;
string ret = to_string(n / d);
if (n % d == 0)
return sign == 1 ? ret : "-" + ret;
else //有小数
{
ret = ret + ".";
while (true)
{
n = n % d;
n *= 10;
if(n % d == 0)//刚好除尽
{
ret += to_string(n / d);
return (sign == 1) ? ret : "-" + ret;
}
else
{
if(m.find(n) == m.end()) //map<被除数,位置>
{
ret += to_string(n / d);
m[n] = ret.size() - 1;
}
else //如果找到,那就肯定除不尽,是无穷的。
{
int pos = m[n];
ret = ret.substr(0, pos) + "(" + ret.substr(pos) + ")";
return (sign == 1) ? ret : "-" + ret;
}
}
}
}
}
};