Skip to content

Commit cf5ab56

Browse files
committed
Add Q166
1 parent 6261d64 commit cf5ab56

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public:
3+
string fractionToDecimal(int numerator, int denominator) {
4+
string ans;
5+
long long n = numerator;
6+
long long d = denominator;
7+
if (n * d < 0) ans += '-';
8+
n = abs(n);
9+
d = abs(d);
10+
ans += to_string(n/d);
11+
if (n % d == 0) return ans;
12+
13+
ans += '.';
14+
unordered_map<int, int> map;
15+
for (long long r = n%d; r ; r %= d) {
16+
if (map[r] > 0) {
17+
ans.insert(map[r], 1, '(');
18+
ans += ')';
19+
return ans;
20+
}
21+
map[r] = ans.size();
22+
r *= 10;
23+
24+
ans += to_string(r / d);
25+
}
26+
return ans;
27+
}
28+
};

0 commit comments

Comments
 (0)