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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
#ifdef LOCAL
#include <bits/stdc++.h>
using namespace std;
// tree node stuff here...
#endif
static int __initialSetup = []()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}
();
class Solution
{
public:
string fractionToDecimal(long long int numerator, long long int denominator)
{
// GG
// what's the range of input?
string ans = "";
if ((numerator < 0 && denominator > 0) ||
(numerator > 0 && denominator < 0))
ans += "-";
numerator = llabs(numerator);
denominator = llabs(denominator);
ans += to_string(numerator / denominator);
numerator %= denominator;
if (numerator != 0) {
ans += ".";
string decimal = "";
// you CAN'T look at quotient!
// look at remainder!
// don't be stupid!
// 1/333
// 1/332
unordered_map<int, int> pos; // remainder, pos
int idx = 0;
pos[numerator] = idx++;
while (numerator != 0) {
numerator *= 10;
auto q = numerator / denominator;
auto r = numerator % denominator;
decimal += to_string(q);
if (pos.find(r) == pos.end()) {
pos[r] = idx++;
} else {
decimal.insert(pos[r], "(");
decimal += ")";
break;
}
numerator = r;
}
ans += decimal;
}
return ans;
}
};
#ifdef LOCAL
int main()
{
return 0;
}
#endif
|