0166.cpp (654B)
1 class Solution { 2 public: 3 string fractionToDecimal(long long n, long long d) const { 4 if (n == 0) return "0"; 5 string res; 6 7 if (n < 0 ^ d < 0) res += '-'; 8 n = abs(n), d = abs(d); 9 10 res += to_string(n / d); 11 if ((n %= d) == 0) return res; 12 res += '.'; 13 14 unordered_map<int, int> um; 15 while (n) { 16 if (um.count(n)) { 17 res.insert(um[n], 1, '('); 18 res += ')'; 19 break; 20 } 21 22 um[n] = size(res); 23 24 n *= 10; 25 res += to_string(n / d); 26 n %= d; 27 } 28 29 return res; 30 } 31 };