Skip to content

Commit a1d801a

Browse files
authored
Create 166. Fraction to Recurring Decimal
1 parent 7f5ab73 commit a1d801a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

166. Fraction to Recurring Decimal

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public:
3+
string fractionToDecimal(int numerator, int denominator) {
4+
5+
if (numerator == 0) return "0";
6+
string res;
7+
if ((numerator < 0) ^ (denominator < 0)) res.push_back('-');
8+
9+
long long n = llabs((long long)numerator);
10+
long long d = llabs((long long)denominator);
11+
12+
res += to_string(n / d);
13+
long long rem = n % d;
14+
if (rem == 0) return res;
15+
16+
res.push_back('.');
17+
unordered_map<long long, int> seen;
18+
19+
while (rem != 0) {
20+
if (seen.find(rem) != seen.end()) {
21+
int pos = seen[rem];
22+
res.insert(pos, "(");
23+
res.push_back(')');
24+
break;
25+
}
26+
seen[rem] = res.size();
27+
rem *= 10;
28+
int digit = rem / d;
29+
res.push_back(char('0' + digit));
30+
rem = rem % d;
31+
}
32+
return res;
33+
}
34+
};

0 commit comments

Comments
 (0)