-
Notifications
You must be signed in to change notification settings - Fork 481
/
0166.cpp
34 lines (33 loc) · 849 Bytes
/
0166.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution
{
public:
string fractionToDecimal(int numerator, int denominator)
{
long long n = numerator, d = denominator;
bool flag = true;
if (n < 0) flag = !flag, n = -n;
if (d < 0) flag = !flag, d = -d;
string res = to_string(n/d);
n %= d;
if (n == 0)
{
if (!flag and res != "0") return "-" + res;
return res;
}
res += '.';
unordered_map<long long, int> m;
while (n)
{
if (m.count(n))
{
res = res.substr(0, m[n]) + "(" + res.substr(m[n]) +")";
break;
}
else m[n] = res.size();
n *= 10ll;
res += to_string(n/d);
n %= d;
}
return flag ? res : "-" + res;
}
};