-
Notifications
You must be signed in to change notification settings - Fork 0
/
Fraction to Recurring Decimal.cpp
35 lines (35 loc) · 1.09 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
35
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
string ans = "";
long long nume = numerator;
long long deno = denominator;
if(denominator == 0)return ans;
if(numerator == 0) return "0";
if(denominator < 0 ^ numerator < 0) {
ans += '-';
nume = abs(nume);
deno = abs(deno);
}
ans += to_string(nume / deno);
long long rem = nume % deno * 10;
if(rem == 0) return ans;
ans += '.';
map<long long,int> m;
long long res = 0;
while(rem){
if(m.find(rem) != m.end()){
int begin = m[rem];
string s1 = ans.substr(0,begin);
string s2 = ans.substr(begin);
ans = s1 + '(' + s2 + ')';
break;
}
m[rem] = ans.length();
res = rem / deno;
ans += to_string(res);
rem = rem % deno * 10;
}
return ans;
}
};