-
Notifications
You must be signed in to change notification settings - Fork 0
/
recurring_fraction.cc
38 lines (31 loc) · 1.09 KB
/
recurring_fraction.cc
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
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if (numerator == 0)
return "0";
std::string fraction;
if (numerator < 0 ^ denominator < 0)
fraction.append("-");
long dividend = std::abs(static_cast<long>(numerator));
long divisor = std::abs(static_cast<long>(denominator));
fraction.append(std::to_string(dividend / divisor));
long remainder = dividend % divisor;
if (!remainder)
return fraction;
fraction.append(".");
std::unordered_map<long, int> ht;
while (remainder != 0) {
if (ht.find(remainder) != ht.end()) {
int pos = ht.find(remainder)->second;
fraction.insert(fraction.begin() + pos, '(');
fraction.append(")");
break;
}
ht.emplace(remainder, fraction.size());
remainder *= 10;
fraction.append(std::to_string(remainder / divisor));
remainder %= divisor;
}
return fraction;
}
};