-
Notifications
You must be signed in to change notification settings - Fork 28
/
Fraction_to_Recurring_Decimal.cpp
34 lines (30 loc) · 1.1 KB
/
Fraction_to_Recurring_Decimal.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
34
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
string result = "";
if(denominator == 0) return result;
if(numerator == 0) return "0";
unordered_map<long, int> appeared;
long q = abs((long)numerator / (long)denominator);
result += string((numerator < 0) ^ (denominator < 0), '-');
result += to_string(q);
long r = abs((long)numerator % (long)denominator);
if(r == 0) return result;
result += '.';
while(r) {
appeared[r] = (int)result.length();
r *= 10L;
result += to_string(r / abs((long)denominator));
r %= abs((long)denominator);
if(appeared.find(r) != appeared.end()) {
// string prefix = result.substr(0, appeared[r]);
// string recur = result.substr(appeared[r]);
// result = prefix + '(' + recur + ')';
result.insert(appeared[r], "(");
result += ')';
break;
}
}
return result;
}
};