【LeetCode】166. Fraction to Recurring Decimal

时间:2021-09-08 08:24:34

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)".

Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.

这题就是按定义做。

如果不能整除,就不断进行余数补零除以除数。

维护一个映射表map<long long, int> m, 用来记录每个除数对应返回值ret中的位置。

(1)当出现重复的除数n时,说明找到了循环体,根据m[n]找到ret中位置,加上相应的'('和')'将循环体括起来即可返回。

(2)当余数r为0时,返回ret。

注意点:

1、正负号

2、分子为0

3、可能出现INT_MIN/-1的越界情况,因此第一步现将int转为long long int

class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
// special cases
if(numerator == )
return "";
string ret = "";
// type conversion in case of INT_MIN
long long n = numerator;
long long d = denominator;
// sign
int sign = ;
bool digit = false;
if((n<) ^ (d<))
sign = -;
n = abs(n);
d = abs(d);
unordered_map<long long, int> m; // numerator --> position
while(true)
{
if(n < d)
{
if(digit == false)
{
if(ret == "")
ret = "0.";
else
ret += ".";
digit = true;
}
n *= ;
}
int r = n - n/d*d;
if(r == )
{
ret += to_string(n/d);
if(sign == -)
ret = "-" + ret;
return ret;
}
else
{
if(digit == true)
{// check recurring
if(m.find(n) == m.end())
{
ret += to_string(n/d);
m[n] = ret.size()-;
}
else
{
int pos = m[n];
ret = ret.substr(, pos) + "(" + ret.substr(pos) + ")";
if(sign == -)
ret = "-" + ret;
return ret;
}
}
else
{
ret += to_string(n/d);;
}
n = r;
}
}
}
};

【LeetCode】166. Fraction to Recurring Decimal