leetcode166 Fraction to Recurring Decimal

思路:

模拟。

实现:

 1 class Solution 
 2 {
 3 public:
 4     string fractionToDecimal(int numerator, int denominator) 
 5     {
 6         long long a = numerator, b = denominator;
 7         string ans = "";
 8         if (a * b < 0) ans += '-';
 9         a = abs(a); b = abs(b);
10         ans += to_string(a / b);
11         a %= b;
12         if (!a) return ans;
13         ans += '.';
14         a *= 10;
15         vector<long long> v;
16         map<pair<long long, long long>, int> mp;
17         long long rem = a % b, q = a / b;
18         while (rem && !mp.count(make_pair(rem, q)))
19         {
20             v.push_back(q);
21             mp[make_pair(rem, q)] = v.size() - 1;
22             rem *= 10;
23             q = rem / b;
24             rem %= b;
25         }
26         if (rem == 0) 
27         {
28             v.push_back(q);
29             for (auto it: v) ans += to_string(it);
30         }
31         else
32         {
33             int start = mp[make_pair(rem, q)];
34             for (int i = 0; i < start; i++) ans += to_string(v[i]);
35             ans += '(';
36             for (int i = start; i < v.size(); i++) ans += to_string(v[i]);
37             ans += ')';
38         }
39         return ans;
40     }
41 };
原文地址:https://www.cnblogs.com/wangyiming/p/9845705.html