class Solution {
public:
string itoa(long long i)
{
char buff[100];
sprintf(buff, "%lld", i);
return buff;
}
string fractionToDecimal(int num, int den) {
long long numerator = num;
long long denominator = den;
int neg = 1;
if (numerator > 0 && denominator < 0)
{
neg = -1;
}
if (numerator < 0 && denominator > 0)
{
neg = -1;
}
numerator = abs(numerator);
denominator = abs(denominator);
long long a = numerator / denominator;
if (numerator == a * denominator)
{
return (neg<0?"-":"")+itoa(a);
}
string ret = (neg<0?"-":"")+itoa(a);
ret += ".";
long long left = numerator - a * denominator;
vector<pair<int, int>> c;
int loop = -1;
while (left != 0)
{
left *= 10;
a = left / denominator;
for (int i = 0; i < c.size(); i++)
{
if (c[i].first == a && c[i].second == left)
{
loop = i;
break;
}
}
if (loop != -1)
{
break;
}
if (left < denominator)
{
c.push_back(make_pair(a,left));
continue;
}
c.push_back(make_pair(a, left));
left = left - a * denominator;
if (left == a * denominator)
{
break;
}
}
for (int i = 0; i < c.size(); i++)
{
if (loop == i)
{
ret += "(";
}
ret += itoa(c[i].first);
}
if (loop != -1)
{
ret += ")";
}
return ret;
}
};
public:
string itoa(long long i)
{
char buff[100];
sprintf(buff, "%lld", i);
return buff;
}
string fractionToDecimal(int num, int den) {
long long numerator = num;
long long denominator = den;
int neg = 1;
if (numerator > 0 && denominator < 0)
{
neg = -1;
}
if (numerator < 0 && denominator > 0)
{
neg = -1;
}
numerator = abs(numerator);
denominator = abs(denominator);
long long a = numerator / denominator;
if (numerator == a * denominator)
{
return (neg<0?"-":"")+itoa(a);
}
string ret = (neg<0?"-":"")+itoa(a);
ret += ".";
long long left = numerator - a * denominator;
vector<pair<int, int>> c;
int loop = -1;
while (left != 0)
{
left *= 10;
a = left / denominator;
for (int i = 0; i < c.size(); i++)
{
if (c[i].first == a && c[i].second == left)
{
loop = i;
break;
}
}
if (loop != -1)
{
break;
}
if (left < denominator)
{
c.push_back(make_pair(a,left));
continue;
}
c.push_back(make_pair(a, left));
left = left - a * denominator;
if (left == a * denominator)
{
break;
}
}
for (int i = 0; i < c.size(); i++)
{
if (loop == i)
{
ret += "(";
}
ret += itoa(c[i].first);
}
if (loop != -1)
{
ret += ")";
}
return ret;
}
};
评论
发表评论