File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ string fractionToDecimal(int numerator, int denominator) {
4
+
5
+ if (numerator == 0) return "0";
6
+ string res;
7
+ if ((numerator < 0) ^ (denominator < 0)) res.push_back('-');
8
+
9
+ long long n = llabs((long long)numerator);
10
+ long long d = llabs((long long)denominator);
11
+
12
+ res += to_string(n / d);
13
+ long long rem = n % d;
14
+ if (rem == 0) return res;
15
+
16
+ res.push_back('.');
17
+ unordered_map<long long, int> seen;
18
+
19
+ while (rem != 0) {
20
+ if (seen.find(rem) != seen.end()) {
21
+ int pos = seen[rem];
22
+ res.insert(pos, "(");
23
+ res.push_back(')');
24
+ break;
25
+ }
26
+ seen[rem] = res.size();
27
+ rem *= 10;
28
+ int digit = rem / d;
29
+ res.push_back(char('0' + digit));
30
+ rem = rem % d;
31
+ }
32
+ return res;
33
+ }
34
+ };
You can’t perform that action at this time.
0 commit comments