-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfractionToDecimal.cpp
More file actions
29 lines (29 loc) · 841 Bytes
/
fractionToDecimal.cpp
File metadata and controls
29 lines (29 loc) · 841 Bytes
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
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if (!numerator) return "0";
string res;
if (numerator < 0 ^ denominator < 0) res += '-';
long numer = labs(numerator);
long denom = labs(denominator);
long integral = numer / denom;
res += to_string(integral);
long rmd = numer % denom;
if (!rmd) return res;
res += '.';
rmd *= 10;
unordered_map<long, long> mp;
while (rmd) {
long quotient = rmd / denom;
if (mp.count(rmd)) {
res.insert(mp[rmd], "(");
res += ')';
break;
}
mp[rmd] = res.size();
res += (quotient);
rmd = (rmd % denom) * 10;
}
return res;
}
};