-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFraction_to_Recurring_Decimal.cpp
More file actions
43 lines (42 loc) · 1.16 KB
/
Fraction_to_Recurring_Decimal.cpp
File metadata and controls
43 lines (42 loc) · 1.16 KB
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
35
36
37
38
39
40
41
42
43
# number : 166
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
string result = "";
if (denominator == 0)
return "NaN";
if ((numerator > 0 && denominator < 0) ||
(numerator < 0 && denominator > 0))
result += "-";
long n = abs(static_cast<long>(numerator));
long d = abs(static_cast<long>(denominator));
long v = n / d;
long m = n % d;
result += to_string(v);
if (m == 0)
return result;
result += ".";
unordered_map<long, int> mp;
int index = 0;
while (m != 0) {
if (mp.find(m) != mp.end()) {
result += "()";
break;
}
mp[m] = index++;
n = m * 10;
v = n / d;
result += to_string(v);
m = n % d;
}
if (mp.find(m) != mp.end()) {
int cur = result.size() - 2;
int t = index - mp[m];
while ( t-- > 0) {
swap(result[cur], result[cur - 1]);
cur--;
}
}
return result;
}
};