forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
33 lines (33 loc) · 823 Bytes
/
Solution.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
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) {
return "0";
}
string ans;
bool neg = (numerator > 0) ^ (denominator > 0);
if (neg) {
ans += "-";
}
long long a = abs(1LL * numerator), b = abs(1LL * denominator);
ans += to_string(a / b);
a %= b;
if (a == 0) {
return ans;
}
ans += ".";
unordered_map<long long, int> d;
while (a) {
d[a] = ans.size();
a *= 10;
ans += to_string(a / b);
a %= b;
if (d.contains(a)) {
ans.insert(d[a], "(");
ans += ")";
break;
}
}
return ans;
}
};