Leetcode 166 Solution
This article provides solution to leetcode question 166 (fraction-to-recurring-decimal)
Access this page by simply typing in "lcs 166" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/fraction-to-recurring-decimal
Solution
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
bool sign = false;
if ((numerator > 0 && denominator < 0) || (numerator < 0 && denominator > 0))
sign = true;
int64_t numerator2 = abs((int64_t)numerator);
int64_t denominator2 = abs((int64_t)denominator);
int64_t base = (int64_t)numerator2 / (int64_t)denominator2;
int64_t next = (int64_t)numerator2 % (int64_t)denominator2;
string fraction;
map<int64_t, int> last_pos;
int loop_start = -1;
while (next)
{
if (last_pos.find(next) != last_pos.end())
{
loop_start = last_pos[next];
break;
}
last_pos[next] = fraction.size();
fraction.push_back(next * 10 / denominator2 + '0');
next = (next * 10) % denominator2;
}
string res = (sign ? "-" : "") + to_string(base);
if (fraction.size())
{
if (loop_start == -1)
{
res = res + "." + fraction;
}
else
{
res = res + "." + fraction.substr(0, loop_start) + "(" + fraction.substr(loop_start) + ")";
}
}
return res;
}
};