-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path166.cpp
28 lines (27 loc) · 934 Bytes
/
166.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
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
bool nega = false;
long num = numerator, den = denominator;
if (num * den < 0) nega = true;
num = abs(num), den = abs(den);
long quotient = num / den, remainder = num % den;
string ans = remainder > 0 ? to_string(quotient) + "." : to_string(quotient);
while (remainder > 0) {
if (rem.count(remainder)) {
string repitition = ans.substr(rem[remainder]);
ans = ans.substr(0, rem[remainder]) + "(" + repitition + ")";
break;
}
rem[remainder] = ans.size();
num = remainder * 10;
quotient = num / den;
remainder = num % den;
ans += to_string(quotient);
}
if (nega) return "-" + ans;
return ans;
}
private:
map<int, int> rem;
};