leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0166.cpp (654B)
0 class Solution {
1 public:
2 string fractionToDecimal(long long n, long long d) const {
3 if (n == 0) return "0";
4 string res;
6 if (n < 0 ^ d < 0) res += '-';
7 n = abs(n), d = abs(d);
9 res += to_string(n / d);
10 if ((n %= d) == 0) return res;
11 res += '.';
13 unordered_map<int, int> um;
14 while (n) {
15 if (um.count(n)) {
16 res.insert(um[n], 1, '(');
17 res += ')';
18 break;
19 }
21 um[n] = size(res);
23 n *= 10;
24 res += to_string(n / d);
25 n %= d;
26 }
28 return res;
29 }
30 };