forked from moranzcw/LeetCode-NOTES
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.cpp
61 lines (56 loc) · 1.69 KB
/
solution.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
return Helper(numerator, denominator);
}
string Helper(long long numerator, long long denominator)
{
//convert to 64_int in case INT_MIN/-1 overflow
//special case
if(denominator == 0)
return "";
else if(numerator == 0)
return "0";
string ret = "";
if((numerator<0) ^ (denominator<0))
{//one of them is negative, with bit or
ret += '-';
numerator = abs(numerator);
denominator = abs(denominator);
}
//integer part
if(numerator/denominator == 0)
//integer part is 0
ret += '0';
else
{
long long quotient = numerator/denominator;
ret += std::to_string(quotient);
if(numerator%denominator == 0)
//divisible
return ret;
else
//not divisible, numerator as remainder
numerator -= (quotient*denominator);
}
//decimal part
ret += '.';
string demical;
map<long long, int> m; //<remainder, index> pair
long long r = numerator;
while(r)
{
if(m.find(r) != m.end())
{//remainder
ret.insert(m[r], 1, '('); //insert (iterator p, size_t n, char c);
ret += ')';
break;
}
m[r] = ret.size();
r *= 10; //next digit
ret += std::to_string(r/denominator);
r %= denominator;
}
return ret;
}
};