fork(10) download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. string solve(int numerator, int denominator) {
  5.  
  6. int64_t n = numerator, d = denominator;
  7. // zero numerator
  8. if (n == 0) return "0";
  9.  
  10. string res;
  11. // determine the sign
  12. if (n < 0 ^ d < 0) res += '-';
  13.  
  14. // remove sign of operands
  15. n = abs(n), d = abs(d);
  16.  
  17. // append integral part
  18. res += to_string((n / d));
  19.  
  20. // in case no fractional part
  21. if (n % d == 0) return res;
  22.  
  23. res += '.';
  24.  
  25. unordered_map<int, int> map;
  26.  
  27. // simulate the division process
  28. for (int64_t r = n % d; r; r %= d) {
  29.  
  30. // meet a known remainder
  31. // so we reach the end of the repeating part
  32. if (map.find(r) != map.end()) {
  33. // insert '(' at the start position where we first saw the remainder
  34. res.insert(map[r], 1, '(');
  35. res += ')';
  36. break;
  37. }
  38.  
  39. // the remainder is first seen
  40. // remember the current position for it
  41. map[r] = res.size();
  42.  
  43. r *= 10;
  44.  
  45. // append the quotient digit
  46. res.push_back((char)('0' + (r / d)));
  47. }
  48.  
  49. return res;
  50. }
  51.  
  52. int main() {
  53.  
  54. cout << solve(1, 2) << endl;
  55. return 0;
  56. }
  57.  
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
0.5